ES Modules: Import and Export

Intermediate · 17 min

How `import`/`export` make a module's dependencies readable without running it, why exported bindings stay live, and how CommonJS's `require` differs.

Before thisError Handling and Custom Errors

Dave Gray · 17 min

ES Modules: Import and Export

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Dave GrayReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • `export` marks a binding as available outside a file; `import` pulls specific bindings in by name, so a module's public surface is explicit instead of implied by load order.
  • A file can have any number of named exports but at most one default export — named exports are for a module with several things to offer, default export is for a module that *is* one thing.
  • Because `import`/`export` statements are fixed text at the top level (never inside an `if` or a function, never with a computed name), a tool can figure out a module's entire dependency graph just by reading it, before running a single line.
  • An imported binding is live, not copied: if the exporting module later reassigns that binding, every file that imported it sees the new value — `import` gives you a window onto the original variable, not a snapshot of it at import time.
  • CommonJS's `require`/`module.exports` solves the same problem by running the required file and handing back whatever object it built — that's a runtime copy of values at the moment of the call, which is why it can't offer static analysis or live bindings the way ESM does.

The problem modules solve

Before ES modules existed, JavaScript had no built-in way to split a program across files and say which pieces each file needed from which other file. The old fix was to drop a pile of <script> tags on a page in the right order and hope every file’s top-level variables landed in one shared global scope without colliding. That works until it doesn’t — two files define a variable called data, load order quietly breaks, and nothing in the language tells you why.

A module system fixes this by giving every file its own private scope and a deliberate, written-down way to open a door between files: export on the giving end, import on the receiving end. Nothing a module doesn’t export leaks out, and nothing reaches in except what’s explicitly asked for.

Named exports, default exports, and reading them back

A file can export as many named things as it wants — functions, classes, plain values — each pulled in elsewhere by matching its exact name:

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

// main.js
import { add, PI } from "./math.js";

It can also have exactly one export default, for the case where a module really represents one single thing rather than a bag of utilities. A default import can be named anything on the way in, since there’s no name to match against:

// Logger.js
export default class Logger { /* ... */ }

// main.js
import AnyNameWorks from "./Logger.js";

Mixing both is legal — a module can have a default export plus a few named helpers alongside it — but if you’re reaching for both in the same file, double check the file is doing one job, not two unrelated ones wearing a trenchcoat.

Why this syntax can be read without being run

import and export statements are restricted on purpose: they have to sit at the top level of a file, and the module name has to be a literal string, never a variable or a function call. That restriction is what makes a module graph statically analyzable — a bundler, a linter, or your editor can read a file’s imports and know exactly what it depends on without executing a single line of it. That’s how tools figure out which exports are actually used anywhere (so the unused ones can be deleted from the final bundle, a trick called tree-shaking) and how your editor can jump straight to a function’s definition in another file.

The video walks through the day-to-day mechanics of this — named versus default exports, and how an import statement actually resolves — which covers the syntax takeaways directly. The static-analysis and live-binding points below go a layer deeper than a syntax tour usually goes, so hold onto them even after the video’s examples make sense.

Live bindings: not what most people expect

Here’s the part that trips people up coming from almost any other sharing mechanism: an ES module export isn’t a copy of a value, frozen at the moment you imported it. It’s a live reference to the exporting module’s own variable.

// 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 SAME imported binding updated itself

Nothing in main.js reassigned count directly — in fact you can’t; an imported binding is read-only from the importer’s side. But calling increment(), which lives inside counter.js and mutates its own count, is visible immediately to every file that imported it. You’re not holding a photograph of the value; you’re looking through a window at the real thing.

How CommonJS does it differently

If you’ve seen Node code with require("./math") and module.exports = {}, you’ve seen the older alternative: CommonJS. Conceptually, require runs the target file top to bottom and hands back whatever object module.exports points to at the moment the file finished running. That’s a one-time snapshot, not a live binding — if the required module reassigns module.exports.count afterward, code that already required it keeps whatever it grabbed the first time.

That difference cascades: because require is an ordinary function call, its argument can be any expression, computed at runtime — which means a tool can’t know what a CommonJS file depends on without actually running it. ESM trades that flexibility for predictability. This lesson stays at the language-level syntax; the mechanics of how Node actually resolves and interoperates between the two module systems is nodejs’s job, not this roadmap’s.

Where this sits in the language

Everything up to this group assumed a single file, or at least treated “file boundaries” as a non-issue. Error handling, promises, classes — all of it works the same whether your whole program lives in one file or fifty. Modules are the language’s answer to organizing code at the scale where one file stops being enough, and they’re worth learning well before you touch a framework, since every framework’s “component” system is built on top of this same import/export boundary.

Check yourself

  1. 01What's the practical difference between a named export and a default export, and when would you reach for each?

    A named export is one of possibly several things a module offers, imported by matching its exact name (`import { foo } from './x'`); a default export is the one thing a module is about, imported under whatever name you like (`import foo from './x'`). Use named exports for a utilities file with many small pieces, default export for a file that represents one main thing, like a single component or class.

  2. 02Why can a bundler statically analyze an ES module's dependencies, but not a CommonJS module that does `const dep = require(getDepName())`?

    ESM `import` statements are a fixed, unconditional, top-level syntax — the string naming the module is always a literal, never computed — so a tool can read the whole dependency graph without executing anything. CommonJS `require` is just a function call; if the argument is computed from a function call, you can't know which module gets loaded without actually running the code.

  3. 03A module exports `let count = 0` and later does `count++` inside a function the module also exports. What does an importer see if it reads `count` after calling that function?

    The updated value. ESM exports are live bindings — the importing file isn't holding a copy made at import time, it's looking at the same variable the exporting module owns. Once that module's internal code changes `count`, every importer's view of it changes too.

  4. 04How does CommonJS's `module.exports` fundamentally differ from an ES module's exports, beyond just syntax?

    `module.exports` is an ordinary object, built by running the file's code top to bottom and assigning whatever values exist *at that moment* — importers get a snapshot. ESM exports are references to the live variables themselves, resolved as bindings rather than as one-time value copies, which is what makes them stay in sync after the fact.

  5. 05Why does it matter that import/export statements can't be placed inside a conditional or a function body?

    It's what makes the module system statically analyzable. If `import` could appear anywhere, figuring out what a file depends on would require actually running it to see which branch executes — defeating the whole point of being able to build a dependency graph, tree-shake unused exports, and catch a broken import before the program ever runs.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark