CommonJS and ES modules

Topic 1 of 4 in Modules & packages7 min readIntermediateFree course

Overview

Every Node.js file is a module with its own private scope. To share functions, classes or values between files, a module exports them and another module imports them.

For historical reasons, Node has two module systems:

  • CommonJS (CJS) — Node’s original system, using require() and module.exports. It dates from 2009, before JavaScript had modules of its own.
  • ES modules (ESM) — the official JavaScript standard, using import and export. The same syntax works in browsers, Deno, Bun and bundlers.

New code should use ES modules. But millions of packages and existing projects use CommonJS, so you need to read both.

ES modules

JavaScript
// lib/math.js
export const TAX_RATE = 0.18;

export function withTax(amount) {
  return amount * (1 + TAX_RATE);
}

export default function round(n) {
  return Math.round(n * 100) / 100;
}
JavaScript
// main.js
import round, { withTax, TAX_RATE } from './lib/math.js';
import * as math from './lib/math.js';

console.log(round(withTax(100))); // 118

This is exactly the syntax you learned in JavaScript Essentials. Named exports go in braces; one default export per file can be imported under any name.

Turning on ES modules

Node decides which system a file uses by looking at:

File Module system
.mjs always ES module
.cjs always CommonJS
.js with "type": "module" in the nearest package.json ES module
.js without it CommonJS (Node also detects import/export syntax and treats the file as ESM)

The simplest setup: put "type": "module" in package.json and use .js everywhere.

JSON
{
  "name": "my-api",
  "type": "module"
}

Paths must be complete

In ES modules, relative imports need the full file name, including .js:

JavaScript
import { withTax } from './lib/math.js'; // ✓
import { withTax } from './lib/math';    // ✗ ERR_MODULE_NOT_FOUND

Directories aren’t resolved to index.js automatically either — write ./lib/index.js in full.

CommonJS

The same module in CommonJS looks like this:

JavaScript
// lib/math.cjs
const TAX_RATE = 0.18;

function withTax(amount) {
  return amount * (1 + TAX_RATE);
}

module.exports = { TAX_RATE, withTax };
JavaScript
// main.cjs
const { withTax, TAX_RATE } = require('./lib/math.cjs');
const fs = require('node:fs');

require is an ordinary function. It runs synchronously, can be called anywhere (even inside an if), and returns whatever the other file assigned to module.exports. require can leave off the extension and resolve folders to index.js.

How Node finds a module

import from ‘node:fs’ or ‘fs’ loads a built-in module compiled into Node. A relative path like ‘./utils.js’ loads a file next to the current one. A bare name like ‘express’ is searched for in node_modules folders, walking up towards the root, and package.json’s exports field picks the file.

  • Built-in modules — node:fs, node:path, node:http. The node: prefix makes it unambiguous that you mean the built-in, and is the recommended style.
  • Relative paths — start with ./ or ../, resolved from the current file.
  • Bare names — like express or pg, installed packages. Node looks in ./node_modules, then ../node_modules, and so on up to the root of the drive. The package’s package.json ("exports" or "main") says which file to load.

Key differences

ES modules CommonJS
Syntax import / export require() / module.exports
Loading asynchronous, analysed before running synchronous, at the moment of the call
Top-level await ✓ ✗
File extension in imports required optional
__dirname, __filename use import.meta.dirname / import.meta.filename ✓ available
Strict mode always only with 'use strict'
Browser compatible ✓ ✗

Getting the current folder in ESM

CommonJS gives every file __dirname. In ES modules, use import.meta:

JavaScript
import path from 'node:path';

const here = import.meta.dirname;                 // folder of this file
const dataFile = path.join(here, 'data', 'seed.json');

Mixing the two

ES modules can import CommonJS packages — import express from 'express' works even though Express is published as CommonJS. The CommonJS module.exports value becomes the default export, and Node tries to expose its properties as named exports too.

Going the other way, recent Node versions let require() load ES modules as long as they don’t use top-level await. In older code you’ll see the workaround of a dynamic import inside an async function: const { thing } = await import('./thing.mjs');.

Dynamic imports

import() loads a module at runtime and returns a promise. Use it to load something only when needed, or to pick a module based on a condition:

JavaScript
const format = process.env.REPORT_FORMAT ?? 'csv';
const { render } = await import(`./renderers/${format}.js`);

Modules are cached

A module’s code runs once, the first time it’s imported. Every later import gets the same exports object. That makes modules a natural place for shared things like a database connection pool:

JavaScript
// db.js — created once, shared everywhere
import pg from 'pg';
export const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });

Which should I use? ES modules for everything new — they’re the standard, they’re what this course uses, and tools increasingly expect them. Learn to read CommonJS, because you’ll meet it in older projects, tutorials and Stack Overflow answers.

Exercise

Split a script into modules

Move the two helper functions into lib/format.js as named exports, and import them in main.js. Use ES modules ("type": "module").

JavaScript
// main.js
function formatPrice(n) {
  return `₹${n.toFixed(2)}`;
}
function formatDate(d) {
  return d.toISOString().slice(0, 10);
}
console.log(formatPrice(499), formatDate(new Date()));

Summary

  • Node supports CommonJS (require/module.exports) and ES modules (import/export).
  • "type": "module" in package.json makes .js files ES modules; .mjs and .cjs force one or the other.
  • ES module imports need full relative paths with the extension.
  • Built-ins can be imported with the node: prefix, e.g. node:fs/promises.
  • Use ES modules for new projects; know CommonJS because a lot of existing code uses it.