Skip to content
Velloreth
Programming 6 min read

ESM vs CommonJS: The JavaScript Module Systems

import/export or require/module.exports? Learn the differences, the interop rules, and how to migrate a project safely today.

By

The two systems

ESM:

import { readFile } from 'node:fs/promises';
export function greet(name) { return `Hello, ${name}`; }

CommonJS:

const { readFile } = require('node:fs/promises');
function greet(name) { return `Hello, ${name}`; }
module.exports = { greet };

ESM is the standard and CommonJS is Node’s original system.

The differences

ESMCommonJS
Syntaximport / exportrequire / module.exports
StandardyesNode only
Loadingstaticdynamic
Timingasynchronoussynchronous
Top-level awaityesno
Tree shakingyespoorly
this at the topundefinedmodule.exports
File extensionrequired in a relative importoptional

Static versus dynamic

ESM is static. The imports are known before the code runs.

import { a } from './a.js';   // always loaded

CommonJS is dynamic. A require can be inside a condition.

if (process.env.NODE_ENV === 'production') {
  logger = require('./prod-logger');
} else {
  logger = require('./dev-logger');
}

The consequence: a bundler can analyse ESM and remove an unused export, and it cannot do the same for CommonJS.

The file extension

FileSystem
.mjsalways ESM
.cjsalways CommonJS
.jsdecided by type in package.json
{
  "type": "module"
}

With type: module, every .js file is ESM.

Without it, every .js file is CommonJS.

The extension is required in an ESM relative import.

import { a } from './a.js';   // correct
import { a } from './a';      // error in ESM

The interop

An ESM file importing a CommonJS file:

import pkg from 'commonjs-package';   // the default is module.exports
import { named } from 'commonjs-package';  // may work, by analysis

A CommonJS file importing an ESM file:

// Not allowed with require
const mod = await import('esm-package');   // a dynamic import

The rules:

  • ESM can import CommonJS with a default import
  • A named import from CommonJS may work, and it is not guaranteed
  • CommonJS cannot require an ESM file, only import() it
  • The interop is the source of most of the confusion

The globals

__dirname and __filename do not exist in ESM.

// CommonJS
const dir = __dirname;

// ESM
import { fileURLToPath } from 'node:url';
import { dirname } from 'node:path';
const dir = dirname(fileURLToPath(import.meta.url));

require does not exist in ESM.

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

this at the top level is undefined in ESM and module.exports in CommonJS.

Tree shaking

The removal of unused exports from a bundle.

It works with ESM because the imports and exports are static.

// Only `add` is included in the bundle
import { add } from './math.js';

It works poorly with CommonJS because a require is dynamic.

The practical consequence: a library that ships CommonJS is harder to tree-shake, which is why many libraries now ship both.

The migration

1. Add type: module to package.json.

2. Replace the syntax.

// Before
const fs = require('fs');
module.exports = { read };

// After
import fs from 'node:fs';
export { read };

3. Add the file extensions to the relative imports.

4. Replace __dirname and __filename.

5. Replace a dynamic require with a dynamic import().

6. Update the tooling. A test runner, a bundler and a linter may need a config change.

7. Do it one package at a time in a monorepo.

Why the module system matters

The module system decides how a program is split into files, how the dependencies are resolved, and what a bundler can do with the result. A static system such as ESM lets a bundler build a graph before the code runs, which is what makes tree shaking possible and what makes a circular dependency visible at build time rather than at run time. A dynamic system such as CommonJS resolves a dependency when the require is reached, which is more flexible and less analysable. The practical consequence is that a library shipping ESM is easier to optimise, a library shipping CommonJS is harder, and a project that mixes the two pays an interop cost at every boundary. That is why the ecosystem has been moving to ESM, and why a new project should start there.

The circular dependency

A circular dependency is a module that imports a module that imports it back. In ESM the binding is live, so the import is resolved to the current value when it is used, and a circular dependency often works. In CommonJS the value is copied at the moment of the require, so a circular dependency can produce an empty object, because the module was not finished when it was required. The symptom is a property that is undefined at start-up and defined later, which is a confusing bug. The fix is to break the cycle, usually by moving the shared value into a third module that both import. A build tool can report the cycle, and a lint rule can prevent a new one.

The package exports field

A modern package declares its entry points in the exports field, which is what lets it ship both an ESM and a CommonJS build. The field maps a condition to a file, and the conditions are import, require, types and default. A bundler or a runtime picks the condition that matches how the package is being loaded, so an ESM consumer gets the ESM build and a CommonJS consumer gets the CommonJS build. The field also restricts what a consumer can import, because a path that is not listed is not accessible, which is a deliberate encapsulation. The common mistake is to add the field without the types condition, which breaks the TypeScript resolution, or to list the conditions in the wrong order, because the first match wins. A package that ships both builds is the smoothest path for its consumers, and it is the reason the field exists.

Common mistakes

A missing file extension. An ESM relative import fails.

require in an ESM file. Not defined.

__dirname in an ESM file. Not defined.

A named import from a CommonJS package. May be undefined.

A require of an ESM package. Not allowed.

A mixed project with no convention. Confusion.

A .js file assumed to be ESM. The type field decides.

A dynamic require in a bundler. The bundle includes everything.

A top-level await in CommonJS. Not allowed.

A quotable summary

ESM uses import and export, is the language standard, and is static and asynchronous, while CommonJS uses require and module.exports, is Node’s original system, and is dynamic and synchronous. A .mjs file is always ESM and a .cjs file is always CommonJS, and a .js file is decided by the type field in package.json. ESM enables tree shaking, and the interop between the two is the source of most of the confusion.

For the related topics, see javascript-modules-guide and package-json-explained. For the broader context, npm-vs-yarn-vs-pnpm and javascript-performance-tips.

Frequently asked questions

What is the difference between ESM and CommonJS?
ESM uses import and export, is the language standard, and is static and asynchronous. CommonJS uses require and module.exports, is Node's original system, and is dynamic and synchronous. ESM is the modern choice and CommonJS is the legacy one.
Can I use both in one project?
Yes, with care. A CommonJS file can require an ESM file only with a dynamic import, and an ESM file can import a CommonJS file with a default import. The interop is the source of most of the confusion, so a project should pick one and use it consistently.
What does type: module in package.json do?
It makes every .js file in the package an ES module. Without it, a .js file is CommonJS. A .mjs file is always ESM and a .cjs file is always CommonJS, regardless of the setting.
Why is ESM asynchronous?
Because the module graph is loaded before the code runs, and a top-level await is allowed. CommonJS loads a module synchronously when the require is reached, which is why a require can be inside a condition.
What is tree shaking?
It is the removal of unused exports from a bundle. It works with ESM because the imports and exports are static and known at build time. It works poorly with CommonJS because a require is dynamic and the bundler cannot prove which exports are used.
How do I migrate from CommonJS to ESM?
Add type: module to package.json, rename the files if needed, replace require with import and module.exports with export, add the file extensions to the relative imports, and replace __dirname and __filename with the import.meta.url equivalents. Do it in one package at a time.