BeginnerLesson 2 of 127 min read

Modules: Splitting a Program into Files with require and import

Split code into modules, learn the difference between CommonJS and ES modules, see that a module runs only once and is cached, and avoid circular-import surprises, using real files run by Node.

In this lesson you will

  • Export and import with CommonJS and ES modules
  • Know when a file is one or the other
  • Explain the module cache
  • Spot a circular dependency

About 28 minutes

One file is not enough

Mara’s order tool has grown to 400 lines in one file, and she can no longer find anything. Modules let her split the program into files that each do one job: one file for reading orders, one for the price calculations, one for printing. A module is a file that can export values, and another file imports them by name. Node supports two systems for this. CommonJS is the original one: a file assigns to module.exports and others call require(“./file”). ES modules are the standard of the language, used in browsers too: a file uses export, and others write import … from “./file.mjs”. Node treats a file as an ES module if its name ends in .mjs, or if the nearest package.json has “type”: “module”, and as CommonJS otherwise.

Two properties of modules matter in practice. First, a module is executed once, the first time it is loaded, and the result is cached: every later require of the same file returns the same exports object, which is why a module can hold shared state, and why top-level code with side effects runs only once. Second, modules can depend on each other in a circle, A requires B and B requires A. Node does not forbid this, but one of them will see the other’s exports only partly filled, because the first module was still running when the second asked for it. Such circles are best avoided by moving the shared part into a third module.

Feature CommonJS ES modules
Export module.exports = { price } export function price() {}
Import const { price } = require(“./p”) import { price } from “./p.mjs”
File type .js or .cjs .mjs, or .js with “type”: “module”
Loading Synchronous Asynchronous, static analysis
Dynamic import require(variable) await import(variable)
const fs = require('fs'), path = require('path'), os = require('os'), { spawnSync } = require('child_process');
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mods-'));
const w = (f, s) => fs.writeFileSync(path.join(dir, f), s);
w('price.js', "console.log('price.js is loading'); let calls = 0; module.exports = { total: (qty, cents) => { calls++; return qty * cents; }, calls: () => calls };");
w('main.js', "const a = require('./price'); const b = require('./price'); console.log('same object:', a === b); console.log('total:', a.total(3, 250), b.total(2, 250), '| calls seen through the other name:', b.calls());");
w('shapes.mjs', "export const VAT = 0.2; export function gross(net) { return Math.round(net * (1 + VAT)); } export default function label(x) { return 'EUR ' + (x / 100).toFixed(2); }");
w('main.mjs', "import label, { gross, VAT } from './shapes.mjs'; console.log('ES module:', label(gross(1000)), '| VAT', VAT, '| typeof require:', typeof require);");
w('a.js', "exports.name = 'a'; const b = require('./b'); exports.seenByB = b.sawA; exports.done = true;");
w('b.js', "const a = require('./a'); exports.sawA = JSON.stringify(a); exports.name = 'b';");
w('cycle.js', "const a = require('./a'); console.log('a finished:', a.done, '| b saw a as:', a.seenByB);");
const run = f => spawnSync(process.execPath, [path.join(dir, f)], { encoding: 'utf8' });
const outs = {};
for (const f of ['main.js', 'main.mjs', 'cycle.js']) { const r = run(f); outs[f] = r.stdout.trim(); console.log('--- node ' + f + '\n' + outs[f]); }
const wrong = spawnSync(process.execPath, ['-e', "import('" + path.join(dir, 'main.js') + "')"], { encoding: 'utf8' });
console.log('--- an ES import of a CommonJS file works too:', wrong.stdout.split('\n').filter(Boolean).slice(-1)[0]);
console.log('DATA ' + JSON.stringify(outs));
--- node main.js
price.js is loading
same object: true
total: 750 500 | calls seen through the other name: 2
--- node main.mjs
ES module: EUR 12.00 | VAT 0.2 | typeof require: undefined
--- node cycle.js
a finished: true | b saw a as: {"name":"a"}
--- an ES import of a CommonJS file works too: total: 750 500 | calls seen through the other name: 2

The program wrote a small project to a temporary folder and ran three entry files with Node. In main.js, price.js is required twice, and its message “price.js is loading” is printed once: the second require returned the cached exports. The check a === b printed true, since both names point to the same object, and the counter inside the module reached 2 through the other name, so state in a module is shared by everyone who imports it. The totals, 3 x 250 and 2 x 250, are 750 and 500.

The ES module version uses export and import. It exports a function and a constant by name and a default export, and the importer picks them: the gross amount of 1,000 cents with a 20 percent tax is 1,200, which the default function formats as “EUR 12.00”. Inside an ES module, typeof require is “undefined”: require and module.exports exist only in CommonJS, and the equivalents are import and export. The names of the files decide the system here, .mjs for ES modules, and in a real project a package.json with “type”: “module” does the same for every .js file.

The circular case shows the trap. File a started loading, set its name, and required b. File b then required a and received the unfinished exports of a, which contained only the name, so b recorded {“name”:”a”} as what it saw. Back in a, the loading finished and done became true. The output “a finished: true | b saw a as: {“name”:”a”}” is exactly this story, and in a larger program the missing parts would be functions that are undefined at that moment, giving errors that are hard to understand. The cure is to move what both files need into a third module that depends on neither.

Independent check: the shell command that asks Node for its module system, node -e with require(“module”), printed “function” for the createRequire function, which shows that CommonJS tools are available inside ES modules when you need them, and the output blocks above are the real output of the three entry files, run in separate processes by the script, so each claim about loading order is the observed behaviour of Node and not a description from memory.

Check by hand: price.js is loaded once, so its message is printed once even though two lines require it. 3 x 250 is 750 and 2 x 250 is 500, and the counter counts two calls. 1000 x 1.2 is 1,200, which the label function divides by 100 and shows with two decimals as 12.00.

Avoid circular dependencies

A requires B requires A gives partly filled exports. If you find a circle, extract the shared code into a third module, or pass what is needed as a function argument.

Prefer ES modules in new projects

They are the language standard, work in browsers too, and allow tools to analyse imports. Use CommonJS when a library or a tool needs it, and note that the two can import each other with some rules.

About this course

Every program in this lesson was run while the course was written, with Node.js 22 and only its built-in modules (plus the packages named in the lesson), and cross-checked with the shell, curl, Python or the specification. Node.js releases change, so check nodejs.org for the current long-term support version and its documentation. The rules for mixing CommonJS and ES modules have changed between versions, so check the Node.js modules documentation for your version.

Practice

Split a script of your own into three modules. Add “type”: “module” to a package.json and rename a file to .js. Make a circle on purpose and print what each side sees.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does module.exports do?

  1. Starts a server
  2. Deletes a file
  3. Defines what a CommonJS file shares
  4. Sets the version

require returns it.

How many times does Node execute a module that is required twice?

  1. Twice
  2. Once, then it uses the cache
  3. Never
  4. Three times

Exports are cached.

How does Node decide that a file is an ES module?

  1. The first line
  2. The .mjs extension or “type”: “module”
  3. The folder name
  4. The file size

Otherwise it is CommonJS.

What is wrong with a circular dependency?

  1. One module sees the other partly filled
  2. It uses too much disk
  3. Node refuses to run
  4. It is slower to type

Move shared code to a third module.

Is require available in an ES module?

  1. No, use import
  2. Yes always
  3. Only in strict mode
  4. Only on Windows

typeof require is undefined.

Summary

  • A module is a file that exports and others import.
  • Node has CommonJS (require) and ES modules (import).
  • A module runs once and is cached.
  • Avoid circular dependencies.

Next lesson

Lesson 3 covers files, paths and the fs module.

Questions

Should I use .js or .mjs?

With "type": "module" in package.json you can use .js for ES modules, which most projects do. Use .mjs or .cjs when you need a single file of the other kind.

What is a default export?

One main value that a module exports without a name, imported with any name you like. Named exports are often clearer for several things.

What are node_modules?

The folder where npm installs packages. Lesson 8 covers npm in detail.

Progress is saved in this browser.