import, export and What Modules Changed
Modules are not just a way to split files. They changed when code runs, what an import actually holds, and how many times a file is evaluated.
Named and default exports, and three things that surprise people: an import is a live view rather than a copy, a module is evaluated once no matter how often it is imported, and imports are hoisted so order in the file does not control order of execution.
EXERCISE
1The Two Kinds of Export
Named and default exports differ in more than syntax, and the choice affects tooling as much as readability.
Named exports, which are the ones to prefer:
// math.js
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
// or collected at the bottom, which is often clearer
const subtract = (a, b) => a - b;
export { subtract };
// app.js
import { PI, add } from "./math.js";
import { add as sum } from "./math.js";
import * as math from "./math.js";
console.log(math.PI, math.add(1, 2));
The names are fixed at both ends. Importing something that does not exist is an error before the code runs:
import { addd } from "./math.js";
// SyntaxError: The requested module does not provide an export named 'addd'
That check happens at parse time, which is possible only because import statements are static. It is the main practical reason named exports are worth preferring.
Default exports, one per module:
// Button.js
export default function Button() { /* ... */ }
// app.js
import Button from "./Button.js";
import AnythingIWant from "./Button.js"; // no error
The importer chooses the name, and nothing checks it. That flexibility is the problem: rename the file's function and every import keeps its old name, so a grep for the real name misses most call sites.
A module can have both, and mixing them is usually a mistake:
// api.js
export default function request(url) { /* ... */ }
export const BASE_URL = "https://api.example.com";
// app.js
import request, { BASE_URL } from "./api.js";
Legal, and it gives you two conventions to remember in one file.
One genuinely useful export form:
// index.js, re-exporting a folder's public surface
export { Button } from "./Button.js";
export { Input } from "./Input.js";
export * from "./helpers.js";
This is a barrel file. It lets consumers write one import rather than four, at the cost of making it harder for a bundler to drop code nobody uses. Worth it for a small public , less so for a large internal folder.
Pro Tip: Prefer named exports. The error on a typo arrives before anything runs, renaming a symbol updates every importer through your editor rather than silently missing them, and a bundler can drop unused named exports far more reliably. Reserve
export defaultfor a module that genuinely has one thing in it.
EXERCISE
2An Import Is a Live View, Not a Copy
This is the thing about modules that most people never learn, and it explains behaviour that looks impossible.
An imported binding is not a copy of a value. It is a live, read-only view of the variable in the exporting module. When that variable changes, every importer sees the new value.
Watch it change:
// 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
Read that again. count was imported once, as a number, and its value changed without being re-imported. No other binding behaves this way: a normal const x = obj.count would have captured 0 forever.
But the view is read-only from the importing side:
import { count } from "./counter.js";
count = 5;
// TypeError: Assignment to constant variable.
Only the module that declared it may change it. Everyone else observes.
Which explains a difference from CommonJS that trips people up:
// CommonJS: module.exports.count is copied at require time
const { count } = require("./counter.js"); // snapshot, stays 0
// ESM: a live binding
import { count } from "./counter.js"; // follows the variable
Code ported from require to import can start behaving differently for exactly this reason, and the change is silent.
A module is evaluated once, however many times it is imported:
// config.js
console.log("config evaluated");
export const config = { loaded: Date.now() };
// a.js
import { config } from "./config.js";
// b.js
import { config } from "./config.js";
// app.js
import "./a.js";
import "./b.js";
// config evaluated <- printed once, not twice
The module registry caches by resolved path. Both files get the same object, not two copies. This is what makes the singleton pattern trivial in modules and also what makes a module with side effects dangerous: the side effect happens once, at a time decided by the import graph rather than by you.
Exporting a mutable binding works and is rarely what you want, because a consumer cannot tell by looking that the value may change under them. Export a function that returns the current value, or an object whose property you update. Both make the mutability visible at the call site.
EXERCISE
3Imports Are Hoisted, and Modules Are Strict
Three behaviours you get automatically, and each one removes a category of bug that classic scripts had.
Imports are hoisted, so position in the file does not control order:
console.log(greeting); // works
import { greeting } from "./messages.js";
Every import in a file is resolved and evaluated before any of that file's own code runs. Putting them at the top is a convention for readers, not a requirement.
Which also means this does not do what it looks like:
if (process.env.NODE_ENV === "development") {
import { devTools } from "./dev.js";
// SyntaxError: imports must be at the top level
}
Static imports cannot be conditional. That is the entire reason import() exists, which is the next lesson.
Module code is always strict, with no directive:
// module.js
undeclared = 1;
// ReferenceError: undeclared is not defined
function f() {
console.log(this); // undefined, not the global object
}
f();
You cannot opt out. This is why Unit 1's note about a constructor called without new throwing rather than writing a global holds in any modern file.
And top-level this is undefined, not the global object:
// classic script
console.log(this === window); // true
// module
console.log(this); // undefined
Code that relied on top-level this to reach the global breaks when moved into a module. Use globalThis if you genuinely need it.
Modules are deferred by default:
// Blocks parsing where it sits:
// <script src="app.js"></script>
// Downloaded in parallel, executed after the document is parsed:
// <script type="module" src="app.js"></script>
A module script behaves as though it had defer on it, so the DOM is ready by the time it runs and you do not need a DOMContentLoaded wrapper.
Scope is per-module, not global:
// a.js
const helper = "a";
// b.js
const helper = "b"; // no conflict, different scopes
Two files that both declare helper at the top level collided in the script-tag era. In modules they cannot see each other at all, and anything shared has to be exported deliberately.
Together these are why "just use modules" is reasonable advice rather than a style preference: four classes of bug stop being possible.
