Skip to the content

Lesson 73 of 296

Modules: ES modules vs CommonJS

What you will learn

  • What a module is and why modules matter
  • ES modules: import and export
  • Named and default exports
  • CommonJS: require and module.exports
  • The differences between the two systems
  • Using modules in the browser and in Node.js
  • Dynamic imports and tree shaking
On this page

What is a module?

A module is a file that keeps its code private by default and chooses what to share with other files. Modules let you split a big program into small files with clear jobs.

Benefits:

  • No global variables leaking between files.
  • Clear dependencies: each file says exactly what it uses.
  • Reusable code.

ES modules (ESM): the standard

ES modules are the official JavaScript module system, built into browsers and Node.js.

Named exports: a file can export many things by name.

// math.js
export const PI = 3.14159;

export function add(a, b) {
  return a + b;
}

export function multiply(a, b) {
  return a * b;
}
// app.js
import { add, PI } from "./math.js";
import { multiply as times } from "./math.js";      rename on import
import * as math from "./math.js";                  everything as one object
math.add(1, 2);

Names must match exactly, inside curly braces.

Default export: one main thing per file.

// logger.js
export default function log(message) {
  console.log(`[LOG] ${message}`);
}
import log from "./logger.js";          no braces; you choose the name
import writeLog from "./logger.js";     also works

Both in one file:

import React, { useState } from "react";

Named or default? Many teams prefer named exports: names stay the same everywhere, editors auto-import them reliably, and renaming is easier. Some frameworks require default exports for certain files (for example, Next.js page files).

Re-exporting (common in index.js files):

export { add, multiply } from "./math.js";

Using ESM in the browser

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

Module scripts are deferred automatically and run in strict mode.

CommonJS (CJS): Node.js's original system

Before ES modules existed, Node.js created CommonJS. You will see it in many Node.js projects and packages.

// math.js
function add(a, b) {
  return a + b;
}
module.exports = { add };
// app.js
const { add } = require("./math");

ESM vs CommonJS

ES modulesCommonJS
Syntaximport / exportrequire() / module.exports
StandardOfficial JavaScript standardCreated by Node.js
WhereBrowsers and Node.jsNode.js (and bundlers)
LoadingStatic: imports are known before the code runsDynamic: require is a normal function call, run at that line
Imports must be at the top levelYes (except import())No, require can be anywhere
Top-level awaitYesNo
Strict modeAlwaysOnly if you add "use strict"
Imported valuesLive bindings: you see updates the exporting module makesA copy of what was exported at that moment
File extension needed in imports (Node.js)Yes, usually: ./math.jsNo: ./math works

Choosing the system in Node.js

  • Add "type": "module" to package.json to make .js files ES modules.
  • Without it, .js files are CommonJS.
  • .mjs files are always ESM; .cjs files are always CommonJS.

For new projects, use ES modules. Mixing the two has rules: ESM can import CommonJS packages, and recent versions of Node.js can also require() many ES modules, but older versions cannot. TypeScript projects add their own settings on top (Part 9).

Dynamic import()

import() loads a module when needed, and returns a promise:

button.addEventListener("click", async () => {
  const { openEditor } = await import("./editor.js");
  openEditor();
});

The editor code is only downloaded when the user clicks. This is called code splitting and makes the first page load faster. React and Next.js use it for lazy loading (Part 12).

Tree shaking

Because ES module imports are static, build tools (bundlers such as Vite, webpack or esbuild) can see exactly which exports are used, and remove unused code from the final bundle. This is called tree shaking. It works much less well with CommonJS.

Circular imports

If a.js imports b.js and b.js imports a.js, one of them may see the other's values before they are ready (undefined, or a TDZ error). If you see strange undefined imports, check for circular dependencies and move shared code to a third file.

Common mistakes

  • Using braces for a default import, or no braces for a named one.
  • Mixing require and import in the same file without understanding the setup.
  • Forgetting the .js extension in Node.js ES modules.
  • Forgetting type="module" in the browser.

How to say it in an interview

"Modules keep code private by default and share it through exports. ES modules use import and export, are the official standard in browsers and Node.js, are statically analysable, which enables tree shaking, run in strict mode, support top-level await and give live bindings. CommonJS uses require and module.exports, loads synchronously at runtime and was Node's original system. In Node, package.json type module or the .mjs and .cjs extensions decide which is used. I use dynamic import for code splitting, and prefer named exports for consistency."

Key words

WordMeaning
ModuleA file with its own scope that exports what it shares
ES modules (ESM)The standard import/export system
CommonJS (CJS)Node.js's original require system
Named exportExported by name; imported with braces
Default exportThe one main export of a file
Dynamic importimport(), loading a module on demand
BundlerA tool that combines modules into files for the browser
Tree shakingRemoving unused exports from the final bundle
Code splittingLoading parts of the code only when needed

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.