Faragiri

Learn Modules and bundlers JavaScript

Two module systems, one measurable difference in when the code runs, and the field in package.json that decides which one a file is written in.

4Sections
3Min read
4Depth

Recommended Before This

0 / 2

Put a console.log as the first line of a file and an import
below it, and the import wins. Measured in Node 25 on 2026-09-02, an ES module
whose first statement prints main starts and whose second imports a
rates module printed rates.mjs body ran first. The CommonJS version
of the same two files printed main starts first.

That is not a detail. ES module imports are hoisted and every imported module
is fully evaluated before any statement of the importing file runs, so
import cannot be conditional and cannot depend on anything computed
above it. require is an ordinary function call that runs where it
is written, which is why it can sit inside an if and why the
printing order reverses.

The two spellings, and what each exports

  • ESM: export const RATES = {...} and
    export default function cost(...), imported as
    import cost, { RATES } from "./rates.mjs"
  • CommonJS: module.exports = { RATES, cost }, imported as
    const { cost } = require("./rates.cjs")

Both answered cost('Tabriz', 10) = 18000. The named and default
distinction is ESM's only real addition, and the default export is the one worth
being sparing with: a named export can be found by searching for its name across
a codebase and a default cannot, because the importing file chooses what to call
it.

Two files, two systems

How ES module and CommonJS exports balance out

Both spellings compute cost('Tabriz', 10) = 18000, yet they differ on when code runs, how defaults work, and how easily tools search exports.

  • ES modules (ESM)import and export syntax
    • Runs imported file before first line of importer
    • Static exports let bundlers drop unused code
    • Named exports stay searchable across codebase
    • Default exports let each importer pick a name
  • CommonJS (CJS)require and module.exports
    • Runs imported file inline at the require call
    • Allowed inside conditional if statements
    • Exports assigned at runtime on module.exports
    • Destructured at call site via require('./rates.cjs')

Both answer cost('Tabriz', 10) = 18000

Favor named ESM exports for new files so references stay searchable, keeping default exports sparing.

Interactive Practice Lab

Edit and run this snippet directly in your browser (zero setup)

JavaScript
const scores = [78, 92, 64, 95, 88];const passed = scores.filter((n) => n >= 70);const avg = passed.reduce((a, b) => a + b, 0) / passed.length;console.log('Passed count:', passed.length);console.log('Average score:', avg.toFixed(1));

Live Big-O Complexity & Binary Search Race Lab

Compare complexity curves at scale and watch Linear vs Binary Search race live.

Which system a file is in, and the extension that overrides it

Node decides per file, and the rule has three steps. A .mjs file
is always ESM and a .cjs file is always CommonJS. A plain
.js file is whatever "type" in the nearest
package.json says, and with no "type": "module" it is CommonJS.
That is the entire mechanism behind the error everybody meets:
Cannot use import statement outside a module means a
.js file was treated as CommonJS.

Per-file mode detection

How Node decides whether a file is ESM or CommonJS

Node follows a strict three-step check per file, which explains both import-outside-module errors and Node 25 cross-loading behavior.

  1. 01Check for .mjs extensionAny .mjs file is always evaluated as an ES module
  2. 02Check for .cjs extensionAny .cjs file is always evaluated as CommonJS
  3. 03Read nearest package.jsonPlain .js follows "type": "module", defaulting to CommonJS when absent
  4. 04Cross-format loading asymmetryNode 25 lets require load .mjs, while runtime CJS exports cannot always guarantee static ESM names

When Node refuses an import in a .js file, it means step three landed on CommonJS.

Mixing is now easier than the folklore says. On Node 25,
require of an .mjs file loaded and ran it, which older
versions refused outright. The remaining asymmetry is that a CommonJS module
cannot be loaded as if it had named ESM exports in every case, because those
names are decided while the module runs rather than before it.

What to run in 2026

ESM is the format to write new code in, free and the standard, and as of 2026
it is what browsers, Node and every bundler agree on. It replaced CommonJS for
new projects, and the reason is not taste: because imports are known before
evaluation, a bundler can tell which exports are never used and drop them, which
is impossible when the exports are assigned at runtime.

Standard 2026 workflow

Moving from CommonJS bundles to ESM and Vite

Static ESM imports let bundlers drop unused exports, and Vite pairs unbundled dev serving with Rollup builds for release.

CommonJS and webpackRuntime exports and full rebuild waits
  1. 01Known import graphBundlers identify and drop unused exports before code runs
  2. 02Unbundled dev serverVite serves ES modules straight to the browser after saving
  3. 03Rollup production buildCompiles optimized release bundles from the same ESM modules
ESM and ViteStatic module graph and instant feedback

Browsers, Node, and modern bundlers all standardize on ESM for new projects.

Vite is the bundler most projects reach for in 2026, free and open source. In
development it serves your ES modules to the browser without bundling at all,
which is why a change appears immediately; for a release it builds with Rollup.
It replaced webpack as the default for new projects, and the practical
difference is the wait between saving a file and seeing it.

Where this stalls people

The stall is a configuration error that reads as a syntax error. Cannot
use import statement outside a module
names the import, so people rewrite
the import, when the fix is one line in package.json or one letter in a
filename. An afternoon goes into the wrong file entirely.

Configuration disguised as syntax

Why import errors send people into the wrong file

Cannot use import statement outside a module points at the import line, even though the cause sits in the filename or package.json.

  • Developer rewrites valid import linesError message names import, wasting time editing working syntax
Cannot use import statement outside a module
  • File extension (.mjs vs .js)A one-letter extension change overrides package defaults immediately
  • "type" in nearest package.jsonAdding "type": "module" tells Node to parse plain .js as ESM

Check extension and package.json type in ten seconds before touching a single import statement.

The check that resolves it in ten seconds: look at the extension, then at
"type" in the nearest package.json, and decide which of the two
systems this file is in before touching any import line. Everything else on this
page follows from that answer. What those modules are actually doing once loaded
is
types, functions
and the parts that surprise people
, adding types across the import boundary
is
types on top of
JavaScript, and what they catch
, and the same dependency question in another
language is
pip, venv, and keeping
projects apart
, all under
the only language a browser
runs
.

Alongside this

Above this