Programming fundamentals · Beginner · 18 min
Use JavaScript modules with import and export
By Padding · Updated 18 Nov 2026
Node.js 26.13 LTS · node:26 image
You will split a Node.js bill-splitting script into three ES modules with named and default exports, load built-ins and code on demand, recognise CommonJS and its errors, and run the same modules in a browser.
On this page
A script that starts at 30 lines soon becomes 300, and one long file gets hard to read, test and share. A module is a file that keeps its own variables private and chooses what other files may use. You mark those parts with export, and another file pulls them in with import.
JavaScript has two module systems. ES modules (ESM), with import and export, are the standard, and both browsers and Node.js run them. CommonJS, with require and module.exports, is what Node.js used before ESM existed, and you will still find it in older projects and packages. This tutorial uses ES modules and shows you enough CommonJS to recognise it and work with it.
You build a small bill splitter: give it a total and a number of people, and it prints each person's share. By the end it is three modules, lib/money.js, lib/split.js and main.js, and the two library modules also run unchanged in a web page. Commands are for a Linux or macOS shell, or WSL on Windows. If you use PowerShell instead, create each file in your editor with the content shown rather than with the cat > file <<'JS' lines, and drop > /dev/null from any command; the node and npm commands are the same.
Step 1 · Set up a project that uses ES modules
Make a folder for the project and give it a package.json, the file npm and Node.js read to learn about a project:
mkdir -p ~/modules-demo
cd ~/modules-demo
npm init -y > /dev/null
npm pkg set type=module
npm pkg get type
node --versionnpm init -ywrites apackage.jsonwith default values. The> /dev/nullhides the long printout.npm pkg set type=moduleadds"type": "module"to that file. This one line tells Node.js to treat every.jsfile in the folder as an ES module.npm pkg get typereads the value back.
Without the type field, Node.js treats .js files as CommonJS. Recent versions can also detect import syntax and switch to ESM on their own, but that costs a second parse of the file and depends on guesswork, so set the field and leave no doubt.
Check it worked
npm pkg get type prints "module" with its quotes, and node --version prints v26. followed by the minor and patch numbers. Open package.json in your editor and you will see the line "type": "module".
Step 2 · Export named values from a module
Create a lib folder and a module for working with money. Amounts are stored as whole numbers of the smallest unit (kobo, cents, pesewas), because computers cannot store most decimal fractions exactly, and 0.1 + 0.2 gives 0.30000000000000004 in JavaScript.
mkdir -p lib
cat > lib/money.js <<'JS'
export const CURRENCY = "NGN";
export function toCents(amount) {
return Math.round(amount * 100);
}
export function formatAmount(cents, currency = CURRENCY) {
const whole = Math.floor(cents / 100).toLocaleString("en-US");
const fraction = String(cents % 100).padStart(2, "0");
return `${currency} ${whole}.${fraction}`;
}
const secretRounding = "not exported";
JSEach export in front of a declaration makes a named export: other files can import it by that exact name. secretRounding has no export, so it stays private to this file. Nothing outside can see it, and two modules can each have a variable with the same name without clashing. Change NGN to your own currency code if you like; the rest of the tutorial shows NGN.
Now write main.js and import two of the names:
cat > main.js <<'JS'
import { toCents, formatAmount } from "./lib/money.js";
console.log(formatAmount(toCents(12500)));
console.log(formatAmount(toCents(19.999), "KES"));
JS
node main.js- The names inside the braces must match the exported names. Ask for one that does not exist and Node.js stops with a
SyntaxErrorbefore running any code. "./lib/money.js"is a relative path:./means "starting from the folder this file is in". Without./or../, Node.js looks for a package innode_modulesinstead.- Import statements go at the top of the file. They run before the rest of the code, so the functions are ready when
console.logcalls them.
Check it worked
The output is two lines: NGN 12,500.00 and KES 20.00. The second amount was rounded to the nearest cent by toCents, and the second argument replaced the default currency.
Step 3 · Add a default export
A module can also have one default export: the main thing it offers. Write the splitting logic as a module whose default export is a function. It imports toCents from the money module, so modules can depend on each other:
cat > lib/split.js <<'JS'
import { toCents } from "./money.js";
export default function splitBill(total, people) {
const cents = toCents(total);
const base = Math.floor(cents / people);
const left = cents - base * people;
return Array.from({ length: people }, (_, i) => (i < left ? base + 1 : base));
}
JSThe path is "./money.js", not "./lib/money.js", because it is relative to split.js, which is already inside lib. The function shares the total out in whole cents and gives the cents left over to the first people, one each, so the shares always add up to the total.
Update main.js to use both modules:
cat > main.js <<'JS'
import splitBill from "./lib/split.js";
import { formatAmount, CURRENCY as currency } from "./lib/money.js";
const shares = splitBill(100, 3);
shares.forEach((share, i) => {
console.log(`Person ${i + 1}: ${formatAmount(share, currency)}`);
});
JS
node main.js- A default import has no braces, and you choose its name.
import splitBillandimport dividewould both work. CURRENCY as currencyimports a named export under a different local name. Use it when a name clashes with one you already have, or is unclear in its new home.- A file can have many named exports but only one default. Many teams prefer named exports everywhere, because a fixed name is easier to search for; you will meet both.
Check it worked
The output is:
Person 1: NGN 33.34
Person 2: NGN 33.33
Person 3: NGN 33.33The three shares add up to exactly NGN 100.00.
Step 4 · See why the .js extension matters
In Node.js, ES module imports need the full file name, extension included. Many tutorials and bundler-based projects leave it out, so see what happens when you do. Write a broken copy of main.js and run it:
cat > broken.js <<'JS'
import splitBill from "./lib/split";
console.log(splitBill(100, 3));
JS
node broken.js || echo "exit status $?"Unlike require() in CommonJS, which tries .js, .json and /index.js for you, an ES module import looks only for the exact name you give it. There is no file called exactly split, so it fails. The || echo part prints the exit status instead of letting the failure stop your shell. Remove the broken file once you have read the error:
rm broken.jsTools such as Vite, webpack and TypeScript in some modes let you leave the extension out because they rewrite the imports before the code runs. Plain Node.js and the browser do not, so write the extension every time.
Check it worked
You see a line with Error [ERR_MODULE_NOT_FOUND]: Cannot find module and the full path ending in /lib/split, a line suggesting something like Did you mean to import "./lib/split.js"?, and then exit status 1. When you meet this error in your own code, check the extension and the relative path first.
Step 5 · Import built-ins and load code only when needed
Node.js's own modules, such as fs for files and process for the running program, are imported with a node: prefix. The prefix makes it clear the module is built in, and no package in node_modules can take its place.
Some code is only needed some of the time. import() with brackets is a dynamic import: it loads a module while the program runs and gives back a promise. Replace main.js with the finished version, which reads its numbers from the command line and only loads the file system module when you ask it to save:
cat > main.js <<'JS'
import { argv, exit } from "node:process";
import splitBill from "./lib/split.js";
import { formatAmount } from "./lib/money.js";
const [total, people] = argv.slice(2, 4).map(Number);
if (!(total > 0) || !Number.isInteger(people) || people < 1) {
console.error("usage: node main.js <total> <people> [--save]");
exit(1);
}
const lines = splitBill(total, people).map(
(share, i) => `Person ${i + 1}: ${formatAmount(share)}`
);
console.log(lines.join("\n"));
if (argv.includes("--save")) {
const { writeFile } = await import("node:fs/promises");
await writeFile("split.txt", lines.join("\n") + "\n", "utf8");
console.log("Saved to split.txt");
}
JS
node main.js 4500 4
node main.js 1000 3 --save
cat split.txt
node main.js || echo "exit status $?"argvis the list of command-line words. The first two are the path tonodeand the script, soargv.slice(2, 4)takes the total and the number of people, and.map(Number)turns the text into numbers.- The
ifrejects a missing, zero or negative total and a number of people that is not a whole number above zero, andexit(1)ends the program with a failure status. await import("node:fs/promises")loads the module only when--saveis present, and the braces pickwriteFileout of it, the same as a static import.awaitat the top level of a file, outside any function, works only in ES modules. In CommonJS you would need to wrap it in anasyncfunction.
For a small built-in like this the saving is tiny. Dynamic import pays off with large modules: a command-line tool that loads its PDF code only for the export command, or a web page that downloads a chart library only when someone opens the chart. On a phone with prepaid data, code that is never downloaded costs nothing.
Check it worked
The first command prints four lines, Person 1: NGN 1,125.00 to Person 4: NGN 1,125.00. The second prints NGN 333.34, NGN 333.33, NGN 333.33 and Saved to split.txt, and cat split.txt shows the same three lines. The last command prints the usage message and exit status 1.
Step 6 · Work with CommonJS in an older file
Sooner or later you copy in code written for CommonJS. Create a file in that style, and a small script that imports it:
cat > service.js <<'JS'
function addServiceCharge(total, percent) {
return total + (total * percent) / 100;
}
module.exports = { addServiceCharge };
JS
cat > try-service.js <<'JS'
import * as service from "./service.js";
console.log(service.addServiceCharge(4000, 10));
JS
node try-service.js || echo "exit status $?"import * as service collects everything a module exports into one object called service. It fails here: because package.json says "type": "module", Node.js reads service.js as an ES module, where module and require do not exist. The error message even suggests the fix.
The fix is the file extension. .cjs always means CommonJS and .mjs always means ES module, whatever package.json says. Rename the file and point the import at the new name:
mv service.js service.cjs
cat > try-service.js <<'JS'
import { addServiceCharge } from "./service.cjs";
console.log(addServiceCharge(4000, 10));
JS
node try-service.jsAn ES module can import a CommonJS file. Node.js reads the names from module.exports, so a named import in braces works as well as * as.
The other direction also works in Node.js 26: require() can load an ES module, as long as that module does not use top-level await. Try both cases from a CommonJS file:
cat > report.cjs <<'JS'
const { formatAmount } = require("./lib/money.js");
console.log(formatAmount(150000));
try {
require("./main.js");
} catch (err) {
console.log(err.code);
}
JS
node report.cjslib/money.js loads fine. main.js contains await at the top level, so require() refuses it with the code ERR_REQUIRE_ASYNC_MODULE. The fix is to use import() from the CommonJS file instead, or to move the project to ES modules. On Node.js versions older than 20.19 and 22.12, any require() of an ES module fails with ERR_REQUIRE_ESM, and you will still see that code in issue trackers and older answers online.
To tell which system a project uses, check three things:
- The
"type"field: runnpm pkg get type."module"means.jsfiles are ES modules;{}(no field) or"commonjs"means CommonJS. - The extension:
.mjsis always ESM and.cjsis always CommonJS. - The code itself:
importandexportat the top level mean ESM;require(andmodule.exportsmean CommonJS.
Check it worked
The first run prints an error with a line starting ReferenceError: module is not defined in ES module scope, then exit status 1. After the rename, node try-service.js prints 4400. node report.cjs prints NGN 1,500.00 and then ERR_REQUIRE_ASYNC_MODULE.
Step 7 · Use the same modules in a browser
Browsers load ES modules with <script type="module">. lib/split.js and lib/money.js use no Node.js built-ins, so they run in a page unchanged. main.js does not, because node:process only exists in Node.js; the page gets its own small entry file instead. Create a page and that entry file in the project folder:
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Split a bill</title>
</head>
<body>
<h1>Split a bill</h1>
<ul id="shares"></ul>
<script type="module" src="./browser.js"></script>
</body>
</html>
HTML
cat > browser.js <<'JS'
import splitBill from "./lib/split.js";
import { formatAmount } from "./lib/money.js";
const list = document.querySelector("#shares");
for (const [i, share] of splitBill(100, 3).entries()) {
const item = document.createElement("li");
item.textContent = `Person ${i + 1}: ${formatAmount(share)}`;
list.append(item);
}
JStype="module"lets the file useimport, gives it its own scope, and makes the browser wait until the page has been read before running it, so#sharesalready exists.- The browser follows each
importand downloadssplit.jsandmoney.jsas separate requests. That suits learning and small sites. For production, a bundler such as Vite combines and shrinks the files so a visitor on a slow mobile connection downloads less.
Opening index.html straight from your file manager will not work: browsers block module scripts from file:// addresses. Serve the folder over HTTP instead. In the project folder, run:
npx --yes http-server@14.1.1 -p 8080 -c-1http-server is a small static file server from npm; -p 8080 picks the port and -c-1 turns off caching so you always see your latest edit. Open http://localhost:8080 in your browser, and press Ctrl+C in the terminal when you are done.
Check it worked
The page shows the heading "Split a bill" and three list items: Person 1: NGN 33.34, Person 2: NGN 33.33 and Person 3: NGN 33.33. In the browser's developer tools, the Network tab lists browser.js, split.js and money.js as separate downloads. If the list is empty, the Console tab shows the reason, most often a missing .js extension or a wrong relative path.
When you have finished, delete the demo folder:
cd ~
rm -rf ~/modules-demoNext steps
- Test
lib/money.jsandlib/split.json their own, now that they are separate files: write your first tests with the Node.js test runner. - Use modules in a bigger program: build a to-do list command-line app in Node.js.
- See how another language does the same job: split Python code into modules.
Part of these paths
Related tutorials
- Split Python code into modules and import themYou will turn one growing Python script into a main script, a converters module and a small package, import them three different ways, and know how Python finds each one.
- Write your first JavaScript tests with the built-in Node.js test runnerYou will write a small price module in JavaScript, cover it with six passing tests using node:test and node:assert, and know how to read a failure and run one test on its own, with no packages installed.
- Build a to-do list command-line app in Node.jsYou will build todo.js, a Node.js command-line app with add, list, done and remove commands that keeps your tasks in a JSON file, gives clear messages for mistakes and is covered by two passing tests.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials