ES modules in Node and interop

Intermediate · 13 min

type module, .mjs and .cjs, import.meta in place of __dirname, import attributes for JSON, and how CommonJS and ESM load each other, including require(esm).

Before thisCommonJS modules

Covalence · 13 min

ES modules in Node and interop

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by CovalenceReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Node decides a file's module system from its extension and the nearest `package.json`: `.mjs` is always ESM, `.cjs` is always CommonJS, and `.js` follows the `"type"` field (`"module"` or the default, `"commonjs"`).
  • ESM differs from CommonJS in ways that bite: relative imports need the full file extension, `__dirname` and `__filename` do not exist (use `import.meta.dirname` and `import.meta.filename`), JSON needs an import attribute, and top-level `await` is allowed.
  • ESM can `import` CommonJS freely: the default import is always `module.exports`, and named imports work only when Node can detect them by static analysis.
  • CommonJS can `require()` an ES module in current Node. This landed unflagged in 22.12 and works on Node 26.13.1, except that a module using top-level `await` throws `ERR_REQUIRE_ASYNC_MODULE`. Older Node, and older advice, said you had to use dynamic `import()`.
  • For new projects, choose ESM (`"type": "module"`). Keep CommonJS for files and dependencies that need it, and bridge with `require()` of ESM, `import()` from CJS, or `createRequire` from ESM.

Two systems, one runtime

Node’s CommonJS predates the language having modules. When ES modules (import and export) became standard, Node could not simply switch: millions of packages used require, and the two systems behave differently at a deep level. CommonJS runs a file and returns whatever it assigned. ESM is parsed first, its imports and exports are known before any code runs, and loading can be asynchronous. So Node supports both and has spent years building bridges. The language side, import, export and live bindings, is covered in ES modules: import and export. This lesson is about how Node treats them.

Choosing the system for a file

Node looks at the file extension and, for .js, at the nearest package.json:

File Module system
.mjs ESM, always
.cjs CommonJS, always
.js with "type": "module" ESM
.js with "type": "commonjs" or no type CommonJS

For a new project, put "type": "module" in package.json and write ESM. The video converts an Express template from CommonJS to ESM on exactly those steps.

What changes when you write ESM

Run these on any current Node. Four differences surprise people coming from require:

1. Relative imports need the extension. import { x } from './lib' fails with ERR_MODULE_NOT_FOUND; write './lib.js'. ESM resolution does not probe the file system for extensions or index.js. Bundlers and TypeScript add it, which can hide the problem until you run Node directly. For TypeScript’s side of this, see module resolution.

2. __dirname and __filename are gone. Use the import.meta object:

console.log(import.meta.dirname);    // directory of this file
console.log(import.meta.filename);   // full path of this file
console.log(import.meta.url);        // file:///... URL
console.log(import.meta.resolve('./lib.mjs'));   // resolved URL

import.meta.dirname and import.meta.filename arrived in Node 20.11. Older code used dirname(fileURLToPath(import.meta.url)), which still works. The URL helpers are explained in path, os and URL. There is also import.meta.main, which is true only in the file you ran directly. It replaces the CommonJS idiom require.main === module, and exists on Node 26.13.1 (it is recent, from the 24 line, so check your version first).

3. JSON needs an import attribute.

import data from './data.json' with { type: 'json' };

Without the with { type: 'json' } part, Node throws ERR_IMPORT_ATTRIBUTE_MISSING.

4. Top-level await works, so const config = await loadConfig(); is legal at the top of an ES module. See dynamic import, top-level await and import.meta. It is also what makes ESM loading asynchronous.

ESM importing CommonJS

This always works:

import counter from './counter.js';   // default import = module.exports, whatever it is

Named imports from a CommonJS file work only when Node can see the names with static analysis of patterns like exports.greet = .... With module.exports = { next } assigned as one object, import { next } from './counter.js' fails with a SyntaxError saying the named export was not found. Import the default and destructure it. Node 26.13.1 behaves this way, and it is the safe habit anyway.

CommonJS loading ESM

For years the rule was “you cannot require() an ES module, use import()”. That changed. From Node 22.12 you can require() an ES module without a flag:

// lib.mjs
export const answer = 42;
export default function hello() { return 'hi'; }

// req.cjs
const m = require('./lib.mjs');
console.log(m.answer, m.default());   // 42 hi

You get the module namespace object. If the module has a default export, the object also carries a __esModule: true marker so that bundler-style interop code behaves. The one hard limit is top-level await: a module that uses it, or imports one that does, throws ERR_REQUIRE_ASYNC_MODULE because require is synchronous. In that case use await import('./lib.mjs'), which works from CommonJS in any version. The video predates require(esm), so ignore advice there that CommonJS must use import(). Library authors have a lot more freedom now: shipping ESM-only no longer breaks CommonJS consumers on current Node. Package.json fields and exports shows how to publish for both.

ESM using require

An ES module has no require. If you need one, for a CommonJS-only dependency or require.resolve, create it:

import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const legacy = require('./counter');

What the video covers

Covalence converts a TypeScript Express template from CommonJS to ES modules and, per its description, explains the differences between the two systems along the way. It is from February 2023, so it predates require(esm), import.meta.dirname and import.meta.main; the sections above cover them, each run on Node 26.13.1. It uses TypeScript, whose side of ESM is in modules and type-only imports. No transcript was available.

Where this fits

You can now write and mix both systems. How Node resolves modules explains how a specifier such as 'express' or './lib.js' becomes a file.

Check yourself

  1. 01A project has `"type": "module"` in `package.json`. Which of these is ESM and which is CommonJS: `a.js`, `b.mjs`, `c.cjs`?

    `a.js` and `b.mjs` are ESM, and `c.cjs` is CommonJS. The `.mjs` and `.cjs` extensions override the `type` field, and `.js` follows it.

  2. 02`import { helper } from './utils'` works in your bundler but fails in plain Node with `ERR_MODULE_NOT_FOUND`. What is the fix and why?

    Write the extension: `'./utils.js'`. Node's ESM loader does not guess extensions or try `index.js` for relative paths, because that would need synchronous file-system probing. Bundlers and TypeScript add that resolution for you, which hides the problem until you run Node directly.

  3. 03How do you get the directory of the current file in an ES module?

    Use `import.meta.dirname` (and `import.meta.filename` for the full path), available in Node 20.11 and later. On older versions the equivalent is `dirname(fileURLToPath(import.meta.url))`.

  4. 04A CommonJS file does `const lib = require('./lib.mjs')` and Node throws `ERR_REQUIRE_ASYNC_MODULE`. What does that tell you?

    `lib.mjs` (or something it imports) uses top-level `await`. `require` is synchronous and cannot wait for it. Switch the caller to `await import('./lib.mjs')`, or remove the top-level `await` from the module graph.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark