Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 133 ยท Modules and Packages

ES Modules

Learn ES modules in Node.js - import and export syntax, default vs named exports, live bindings, top-level await, dynamic import(), import.meta and circular imports.

A program of any size is split into files, and those files need a way to share code. In JavaScript the official way is the ES module system (ESM): a file exports the pieces it wants to share, and other files import them. ES modules are part of the language itself, the same syntax works in browsers and in Node.js, and they are what you should use for all new Node.js code.

Node.js had its own module system long before the language standardised one. That older system, CommonJS, is still everywhere, and you will meet it in older code and packages. This lesson covers ES modules from the ground up; the next lesson covers CommonJS, and Mixing ESM and CommonJS explains how the two talk to each other.

Every example in this tutorial runs as an ES module (the file is main.mjs), so everything you write in the editors on this page is already ESM. Examples that need several files write them to disk first and then import them, so you can see the whole story in one editor.

Named exports and imports

A module is just a file. Everything declared in it is private unless you export it. The most common form is a named export: you put export in front of a declaration, and the importer lists the names it wants in braces.

NODE
// math.mjs
export const PI = 3.14159;

export function area(radius) {
  return PI * radius * radius;
}

const secret = 'not exported';
NODE
// main.mjs
import { PI, area } from './math.mjs';

console.log(PI, area(2));

Our editor has only one file, so the next example writes math.mjs to disk first and then loads it with a dynamic import() (more on that below). The destructuring on the left of await import(...) picks the same names as the braces in a static import.

Node.js Writing a module and importing it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Only PI and area appear in the module's namespace; secret stays private to the file. That is the whole point of modules: you choose what to expose.

Static imports happen first

Because static imports are hoisted, the order of your statements does not decide when a module loads. Node.js reads the file, finds every import line, loads those modules (and their imports, recursively), and only then runs the top of your file. The following program makes that visible with a failing static import placed after a console.log.

Node.js Imports run before your code (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The path module has no export called missing, so linking fails before the first line runs. The error reads SyntaxError: The requested module 'node:path' does not provide an export named 'missing', and the stack trace points at the import line. This early failure is a feature: typos in names are caught at load time, not in the middle of a request.

Default exports

A module can also have one default export, imported without braces and under any name you like. Named and default exports can live together.

NODE
// shape.mjs
export default function describe(shape) {
  return `a ${shape.kind}`;
}
export const SIDES = { triangle: 3, square: 4 };
NODE
import describe, { SIDES } from './shape.mjs';

Default exports look convenient, but many teams prefer named exports only. A named export has one canonical name, so editors can auto-import it and a rename refactors every use. A default export can be imported as describe, d or thing, and the code base slowly drifts.

You can also rename on either side with as, and import everything as a namespace object with * as.

Node.js Renaming and namespace imports

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

export { add, sub as subtract } is the list form: declare things normally, then export them by name at the bottom. The namespace object lists its keys in alphabetical order, and default shows up as an ordinary key named default. Its string tag is Module.

Re-exports

A module can forward exports from another module, which is how an index.mjs gathers the public face of a folder.

NODE
export { add } from './math.mjs';
export * from './strings.mjs';
export { default as describe } from './shape.mjs';

export * re-exports every named export but not the default. Be careful with it in large projects: it hides where a name comes from, and when two export * lines export the same name, that name becomes ambiguous and is silently left out. Section barrel files in the module patterns lesson discusses the cost.

Live bindings

Here is the first surprise for people who know CommonJS. An imported name is not a copy of the value. It is a live, read-only view of the variable inside the exporting module. When the exporter changes the variable, importers see the new value.

Node.js Live bindings and read-only imports

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The importer cannot assign to the binding (TypeError, because module namespace objects are frozen views); only the module that owns the variable can change it. This is why modules that need mutable shared state usually export functions that change it, as increment does here. Live bindings are also what makes circular imports workable, as you will see shortly.

Always write the file extension

CommonJS let you write require('./math') and Node would search for math.js, math.json, math/index.js and more. ES modules do not guess. The specifier must be a full path, extension included. A bare './math' fails, and so does a folder path like './lib' that relied on index.js.

Node.js A missing extension (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The error code is ERR_MODULE_NOT_FOUND. Node does not try extensions, which keeps resolution fast and predictable (browsers work the same way). On your own machine the message shows the full absolute path; we trim it so the output is the same everywhere.

There are three kinds of specifier:

Kind Example Resolved as
Relative or absolute path ./math.mjs, ../lib/db.js A file, extension required
Built-in module node:fs, node:path Part of Node itself; use the node: prefix
Bare name express A package in node_modules (see package.json and npm)

Use the node: prefix for built-ins. It makes it obvious that the import is not an npm package, and some modules (such as node:test and node:sqlite) can only be imported with the prefix.

.mjs, .js and the type field

How does Node decide that a file is an ES module? By its extension and, for .js, by the nearest package.json:

  • .mjs is always an ES module.
  • .cjs is always CommonJS.
  • .js follows the "type" field of the closest package.json: "type": "module" means ESM; "type": "commonjs" (or no field) means CommonJS.
  • A file with no extension, or any other extension, is treated according to --experimental-default-type flags and special rules; avoid it.
JSON
{
  "name": "my-app",
  "type": "module"
}

Setting "type": "module" in your project's package.json is the standard way to write modern Node code with .js files. In our editor the file is named main.mjs, which is why import works without any setup. (Node 22.7 and later also detects ESM syntax in an ambiguous .js file and reruns it as ESM, but relying on that costs startup time and is a fallback, not a plan.)

What is different inside a module

An ES module runs in strict mode automatically, and it does not get the CommonJS variables require, module, exports, __dirname and __filename. Top-level this is undefined.

Node.js What exists and what does not

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

All four checks come back as undefined, and a plain function call also sees this as undefined (strict mode), where a CommonJS script would give you the global object.

import.meta

Instead of __dirname and __filename, ES modules have the import.meta object with information about the current module.

Node.js import.meta

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Property Meaning
import.meta.url The module's own file: URL
import.meta.filename The absolute path of the file (Node 20.11 / 21.2 and later)
import.meta.dirname The folder containing it (same versions)
import.meta.resolve(specifier) Resolves a specifier to a URL string without importing it

dirname and filename only exist for file: modules. If you read old code that uses fileURLToPath(import.meta.url) and path.dirname, it does the same thing; the new properties are just shorter. See The os and path Modules for fileURLToPath.

Top-level await

In a module you may use await directly at the top level, outside any function. You have been seeing it in every example so far. The module's evaluation simply pauses until the promise settles, and any module that imports it waits too.

Node.js Top-level await

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Top-level await is great for startup work: reading a config file, opening a database, loading a template. Use it with care in modules that many others import, because every importer waits for it. A slow top-level await in a shared module delays the whole program's startup. Also remember that an unhandled rejection at the top level crashes the process, which is often what you want at startup.

Dynamic import()

Static import is a declaration: it must be at the top level and its specifier must be a plain string. import() is an expression that returns a promise for the module namespace. You can call it anywhere, with a computed string, and only when you need it. It also works from CommonJS files, which makes it the main bridge between the two systems.

Node.js Choosing a module at runtime

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Typical uses: loading a plugin by name, loading heavy code only on the code path that needs it (faster startup), importing a file you just generated, and loading ES modules from CommonJS. Modules are cached by their resolved URL, so importing the same file twice evaluates it only once.

Never pass untrusted input to import(). A user-controlled specifier can load any file or even a data: URL, which means running code of the attacker's choice. Validate against an allow-list, as a lookup table of known names.

Circular imports

Module A imports B, and B imports A. This is legal in ES modules because bindings are live and modules are evaluated in dependency order. Whichever module finishes loading first can see the other's names, but only after the other has initialised them. Reading a const or let that has not been initialised yet throws a ReferenceError.

Node.js A circular import and the temporal dead zone

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

We started with a.mjs, which imports b.mjs first. So b.mjs runs first, and when it reads a the variable exists but is still in its temporal dead zone, because the line export const a = 'A' has not run yet. Then a.mjs continues and sees b fine.

The robust fixes are structural: move the shared piece into a third module that both import, or only use the other module's exports inside functions that run later (by then everything is initialised). More patterns are in Module Design Patterns.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A file named server.js has no package.json nearby and contains an import statement. In Node.js 24 what is the safest way to make it an ES module?

    The module system is chosen by extension and the nearest package.json type field. .mjs always means ESM; .js means ESM only when type is module.
  2. 2. What does an imported variable such as count from export let count represent?

    ES module bindings are live. When the exporter changes the variable, importers see the new value, but they cannot assign to it themselves.
  3. 3. Why does import './math' fail in an ES module while require('./math') works in CommonJS?

    Relative specifiers in ESM must include the file extension, as in a browser. The failure is ERR_MODULE_NOT_FOUND.
  4. 4. Which replaces __dirname inside an ES module?

    import.meta.dirname (and import.meta.filename) were added in Node 20.11 / 21.2. The older way is path.dirname(fileURLToPath(import.meta.url)).
  5. 5. When is a dynamic import() the right tool?

    import() is an expression returning a promise, so it can run anywhere with a computed specifier. Static imports are hoisted and resolved before your code runs.

Summary

  • ES modules use export and import; they work the same in browsers and Node.js and are the default choice for new code.
  • Named exports have one canonical name; a module may also have one default export. as renames, * as ns imports a namespace object, export ... from re-exports.
  • Imported names are live, read-only bindings, not copies.
  • Static imports are hoisted and resolved before any code runs; relative specifiers need the full file extension; use the node: prefix for built-ins.
  • .mjs is ESM, .cjs is CommonJS, and .js follows "type" in the nearest package.json.
  • Inside ESM: strict mode, top-level this is undefined, no require, __dirname or __filename; use import.meta.url, .filename, .dirname and .resolve().
  • Top-level await pauses module evaluation; dynamic import() loads modules on demand and never with untrusted specifiers.
  • Circular imports work through live bindings but can hit the temporal dead zone; break the cycle with a third module.

Next: CommonJS Modules covers the original Node.js module system you will still meet in many packages.