Skip to content
Velloreth
Programming 8 min read

JavaScript Modules: ESM, CommonJS and How They Differ

Modules split code into files with explicit dependencies. Learn ESM syntax, the CommonJS differences, and the interop gotchas.

By

ES modules

The standard module system, used in browsers and modern Node.

Named exports

// math.js
export function add(a, b) { return a + b; }
export const PI = 3.14159;
export class Vector { }
// main.js
import { add, PI } from './math.js';

Default export

// logger.js
export default function log(message) {
  console.log(message);
}
// main.js
import log from './logger.js';

A module can have one default export and any number of named exports.

export default class User { }
export const ROLES = ['admin', 'user'];
import User, { ROLES } from './user.js';

Renaming

import { add as sum } from './math.js';
export { add as sum };

Namespace import

import * as math from './math.js';
math.add(1, 2);
math.PI;

This imports everything as a single object. It defeats tree shaking, so prefer named imports.

Re-exporting

export { add } from './math.js';
export * from './math.js';
export { default as User } from './user.js';

This is how a barrel file (index.js) aggregates a directory.

CommonJS

The older Node system.

// math.js
function add(a, b) { return a + b; }
const PI = 3.14159;

module.exports = { add, PI };
// main.js
const { add, PI } = require('./math.js');

Or exporting a single value:

module.exports = function log(message) { };
const log = require('./logger.js');

The key differences

ESMCommonJS
Syntaximport / exportrequire / module.exports
AnalysisStaticDynamic
LoadingAsynchronousSynchronous
Tree shakingYesLimited
Top-level awaitYesNo
this at top levelundefinedmodule.exports
Live bindingsYesNo
File extension.mjs or .js with type.cjs or .js without type

Static versus dynamic

ESM imports are resolved before the code runs, which is what enables tree shaking and static analysis.

import { add } from './math.js'; // must be at the top level

CommonJS require is a function call, so it can be conditional.

if (process.env.NODE_ENV === 'development') {
  const debug = require('./debug.js');
}

The ESM equivalent is a dynamic import:

if (process.env.NODE_ENV === 'development') {
  const { debug } = await import('./debug.js');
}

Dynamic import() returns a promise and works in both systems.

Live bindings

ESM exports are live. A change to an exported variable is visible to importers.

// counter.js
export let count = 0;
export function increment() { count++; }
// main.js
import { count, increment } from './counter.js';
console.log(count); // 0
increment();
console.log(count); // 1 — the binding is live

CommonJS copies the value at require time, so the same pattern does not work.

// counter.js
let count = 0;
module.exports = { count, increment: () => count++ };
const { count, increment } = require('./counter.js');
console.log(count); // 0
increment();
console.log(count); // 0 — the copy is stale

This is a subtle difference that causes confusing bugs when migrating.

Top-level await

ESM supports await at the top level of a module.

// config.js
const response = await fetch('/config.json');
export const config = await response.json();

CommonJS does not. The workaround is an async function that is called immediately, which is harder to reason about.

Configuring Node

Node decides the module system from the file extension and package.json.

{
  "type": "module"
}

With "type": "module", .js files are ESM. Without it, .js files are CommonJS.

The extensions always win:

ExtensionAlways
.mjsESM
.cjsCommonJS
.jsDepends on package.json

In the browser

<script type="module" src="/main.js"></script>

Key differences from a classic script:

  • Deferred by default. The module executes after the document is parsed.
  • Strict mode by default. No need for 'use strict'.
  • Scoped. Variables are not added to the global object.
  • CORS applies. Modules must be served with the correct MIME type and CORS headers.
  • Executed once. Importing the same module twice runs it once.

The MIME type matters. A server returning text/plain for a .js file causes the module to fail with a MIME type error.

Interop

Mixing the two systems causes friction.

Importing CommonJS from ESM

import pkg from 'commonjs-package';
const { thing } = pkg;

The default import is the whole module.exports object. Named imports sometimes work, because Node analyses the CommonJS exports statically, but it is not guaranteed.

Importing ESM from CommonJS

const { thing } = await import('esm-package');

require of an ESM module is supported in recent Node versions, but dynamic import() is the reliable approach.

The __dirname problem

__dirname and __filename do not exist in ESM.

// CommonJS
const path = require('path');
const dir = __dirname;

// ESM
import { fileURLToPath } from 'node:url';
import { dirname } from 'node:path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

import.meta.url is the ESM equivalent, and it is a URL rather than a path.

Tree shaking

Bundlers remove unused exports, which reduces bundle size. This works with ESM because the imports are statically analysable.

// utils.js
export function used() { }
export function unused() { }
// main.js
import { used } from './utils.js';

The bundler can see that unused is never imported and drop it.

Things that defeat tree shaking:

  • Namespace imports. import * as utils pulls everything.
  • Side effects. A module that does work on import cannot be dropped.
  • CommonJS. The dynamic require makes analysis unreliable.
  • Re-exporting everything. export * from can pull in more than needed.

The sideEffects field in package.json tells the bundler which files are safe to drop.

{
  "sideEffects": false
}

Circular dependencies

Two modules that import each other create a cycle, and the behaviour depends on which is loaded first.

// a.js
import { b } from './b.js';
export const a = 'a';
console.log(b);

// b.js
import { a } from './a.js';
export const b = 'b';
console.log(a);

With ESM, the bindings are hoisted, so the import exists but may be uninitialised when the module body runs. Accessing it before initialisation throws a ReferenceError about accessing a binding before initialisation.

The fixes:

Extract the shared code into a third module that both import. This is the cleanest solution and usually reveals that the cycle was unnecessary.

Use a dynamic import to defer the load.

// a.js
export async function getB() {
  const { b } = await import('./b.js');
  return b;
}

Restructure the dependency so the cycle does not exist. A cycle usually means two modules are too tightly coupled.

Circular dependencies are a design smell. They make the load order significant and the behaviour hard to reason about.

Module resolution

When you write import x from './thing.js', the specifier is resolved to a file.

Relative specifiers start with ./ or ../ and resolve from the current file.

Bare specifiers like import x from 'lodash' resolve through node_modules in Node, or through the bundler’s resolution in a browser build.

Absolute specifiers start with / and resolve from the server root in a browser.

URL specifiers work in browsers and in Deno.

import x from 'https://cdn.example.com/mod.js';

The extension matters in ESM. Node requires the full filename, including .js, for relative imports. Bundlers often allow omitting it, which is a difference that causes confusion when moving code between environments.

import { add } from './math.js'; // required in Node ESM
import { add } from './math';   // works in some bundlers

Practical guidance

  • Use ESM for new code, in both Node and the browser.
  • Set "type": "module" in package.json for a Node project.
  • Prefer named exports over default exports, for better tooling and refactoring.
  • Avoid namespace imports if bundle size matters.
  • Use dynamic import() for conditional loading.
  • Use import.meta.url instead of __dirname.
  • Do not mix the two systems in one project.
  • Check the MIME type when a browser module fails to load.

For the related guides, see javascript-optional-chaining and javascript-map-and-set. For the broader context, environment-variables-explained and semantic-versioning-explained.

Quotable summary

ES modules use import and export, are statically analysed, and are the standard for both browsers and modern Node, while CommonJS uses require and module.exports, loads synchronously, and remains common in older Node code. ESM imports are live bindings, so a change to an exported variable is visible to importers, whereas CommonJS copies the value at require time and the copy goes stale. ESM is asynchronous in browsers, which is why it supports top-level await and why the file must be served with the correct MIME type. Tree shaking works with ESM because the imports are statically analysable, and it is defeated by namespace imports, side effects, and CommonJS. Mixing the two systems causes interop problems, so pick one per project and be consistent.

Frequently asked questions

What is the difference between ESM and CommonJS?
ESM uses import and export and is statically analysed, so bundlers can tree-shake it. CommonJS uses require and module.exports, loads synchronously, and is evaluated at runtime. ESM is the standard; CommonJS is the older Node system.
What does 'type': 'module' in package.json do?
It tells Node to treat .js files in that package as ES modules. Without it, .js files are CommonJS and ESM must use the .mjs extension.
What is a default export?
A default export is the module's main value, imported without braces: import thing from './thing.js'. A named export is imported with braces: import { thing } from './thing.js'.
Can I use require in an ES module?
Not directly. Use createRequire from the module built-in, or switch to import. In recent Node versions, require of an ESM module is also supported in some cases.
What is tree shaking?
It is the bundler's removal of unused exports. It works with ESM because the imports are statically analysable, so the bundler can tell which exports are never used. CommonJS is harder to analyse, so tree shaking is less effective.
Why does my import fail with 'Cannot use import statement outside a module'?
Because the file is being treated as CommonJS. Add 'type': 'module' to package.json, rename the file to .mjs, or use require instead.