← JavaScript

Intermediate · 13 of 17 · 15 min read

ES modules

Named and default exports, why imports are live bindings rather than copies, and what static analysis buys you.

  • Modules

A module is a file with its own scope that declares what it shares and what it needs. ES modules are the standard form, understood by browsers, Node and every bundler.

Named exports

Any number per module, and the names have to match on both sides:

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

// or declare first and export in one list:
const E = 2.71828;
function subtract(a, b) { return a - b; }
export { E, subtract };
// app.js
import { PI, add } from './math.js';
import { subtract as minus } from './math.js'; // renamed on import
import * as math from './math.js';             // everything as a namespace object

console.log(PI, add(1, 2), minus(5, 3)); // 3.14159 3 2
console.log(Object.keys(math).length);    // every export
console.log(math.add(1, 1));              // 2

A name that is not exported is a build-time error, not a runtime undefined:

// import { nope } from './math.js';
// SyntaxError: The requested module './math.js' does not provide an export named 'nope'

The default export

Exactly one per module — “the main thing this file is”:

// logger.js
export default function log(message) {
  console.log(`[app] ${message}`);
}

// also legal, because a default export takes an expression:
// export default { a: 1 };
// export default class {} ;
// export default 42;
// app.js
import log from './logger.js';          // any name you like — no braces
import whateverIWant from './logger.js'; // the same function
log('started');

A module can have both, which is the common shape for a library:

// api.js
export default function request(url) { /* … */ }
export const TIMEOUT = 5000;
export function get(url) { return request(url); }

// app.js
import request, { TIMEOUT, get } from './api.js'; // default first, then the braces
console.log(TIMEOUT);
Default export Named export
Per module one any number
Import syntax import x from import { x } from
Name at import your choice must match, unless aliased
A typo is caught no — you just name it something else yes, at build time
Renaming it in the source importers keep working importers break visibly
Tree shaking works, but coarser precise

The practical advice most style guides land on: prefer named exports. A default export makes the same thing appear under five different names across a codebase, and a rename in the source is invisible to every importer.

Live bindings, not copies

This is the detail that separates ES modules from CommonJS, and it does get asked:

// counter.js
export let count = 0;
export function increment() { count += 1; }
// app.js
import { count, increment } from './counter.js';

console.log(count); // 0
increment();
console.log(count); // 1 — the imported binding tracks the export
// count = 5;       // TypeError: Assignment to constant variable

An import is a read-only view of the exporting module’s binding, not a snapshot of its value. You can see the exporter’s updates; you cannot write through it.

import * as mod from './counter.js';
// mod.count = 10;  // TypeError — namespace objects are sealed and read-only

Imports are hoisted

The whole graph is resolved and every module is evaluated before the importing module’s first line runs:

// side-effects.js
console.log('module evaluated');

// app.js
console.log('app starting');
import './side-effects.js'; // written here, but runs first
// logs: "module evaluated" then "app starting"

Which means imports cannot be conditional:

// if (isProduction) {
//   import { analytics } from './analytics.js'; // SyntaxError
// }

Dynamic import()

For the conditional case there is the import() function, which returns a promise for the namespace object:

async function maybeLoad(isProduction) {
  if (!isProduction) return null;
  const module = await import('./analytics.js'); // only fetched if we get here
  return module.track;
}

// The default export arrives as `.default`:
async function loadLogger() {
  const { default: log } = await import('./logger.js');
  log('loaded on demand');
}

The three reasons to use it:

  • Code splitting — a route or a modal whose code should not be in the initial bundle.
  • A conditional dependency — a polyfill, or a dev-only tool.
  • A computed path — await import(\./locales/${lang}.js`)`, which a static import cannot express.

It is not a replacement for static imports. It costs a network round trip and defers a type error to runtime, so it is a deliberate choice, not the default.

Side-effect imports and re-exports

import './styles.css';     // run it for its effects, import nothing
import './polyfills.js';

A barrel file re-exports from several modules so consumers have one entry point:

// index.js
export { add, subtract } from './math.js';
export { default as log } from './logger.js'; // promote a default to a name
export * from './utils.js';                   // everything except the default

Modules are different from scripts

Plain <script> Module
Top-level scope global the module’s own
Strict mode opt in always on
this at the top level window undefined
Loading blocking deferred, after parsing
Evaluated more than once yes, per tag no — cached after the first time
await at the top level no yes
// In a module:
console.log(this);           // undefined
const notGlobal = 1;         // not on globalThis
const data = await fetch('/api').then((r) => r.json()); // top-level await is legal

The caching rule is important: a module is evaluated once per URL, however many files import it. That is what makes a module a natural singleton:

// store.js — evaluated once, so every importer shares this object
export const store = { items: [] };

// a.js
import { store } from './store.js';
store.items.push('from a');

// b.js
import { store } from './store.js';
console.log(store.items); // ["from a"] — the same object

Loading them

<script type="module" src="./app.js"></script>
<script type="module">
  import { add } from './math.js';
  console.log(add(1, 2));
</script>

In Node, a file is an ES module when it is named .mjs, or when the nearest package.json has "type": "module". In the browser the specifier must be a real path — ./math.js, with the extension — unless an import map maps a bare name.

Common mistakes

Omitting the file extension in the browser

Mistake. import { add } from './math'. Why it fails. Bundlers resolve that; the browser does not, and the request 404s. What to do instead. Write the extension: './math.js'. It also keeps the code working unbundled.

Two default exports, or a named import for a default one

Mistake. import { log } from './logger.js' when logger.js has export default log. Why it fails. The default export has no name to match. The error says the module provides no export named log, which reads as though the file is wrong. What to do instead. import log from './logger.js', or import { default as log }.

Expecting an import to be a snapshot

Mistake. Assuming an imported value cannot change after you read it. Why it fails. Imports are live bindings; export let means the exporter can change what you see. What to do instead. Export a function or a getter when the value evolves, so the dependency is explicit — and export const when it should not change at all.

Check yourself

3 questions from the bank on what you just read. Answering here does not affect your quiz history.

Which statement about ES modules is true?

How many default and named exports can one module have?

When does the import() *function* make sense instead of a static import statement?

Practise Modules →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.