Developer tools
Modules: import and export
A way to split a program into files: each file hides its own stuff and explicitly gives out what's needed.
Why it exists
A two-thousand-line program in one file is one shared scope: a count at the top easily overwrites a count at the bottom, and the only way to find anything is search. Pages used to load scripts one after another with <script src>, and all of them shared global variables — load order and accidental name clashes broke everything. Modules give each file its own scope and an explicit contract: export is what I give, import is what I need. Code can be read, tested and changed in pieces, and the dependencies are visible in the first lines of a file.
Where it's used
- Any modern frontend: React, Vue, Svelte — each component in its own module, with
importin the first lines of every file. - Project structure:
utils/with helpers,api/with server requests,ui/with the interface, andindex.jsre-exports so a folder can be imported in one line. - Packages from npm:
import { format } from "date-fns"— the sameimport, just a path without./, and the package is looked up in node_modules. - Node.js:
import fs from "node:fs"in.mjsfiles or in a project with"type": "module"in package.json.
Syntax
// math.js
export const PI = 3.14;
export function sum(a, b) { … }
export { sum as add }; // export under another name
// main.js
import { PI, sum } from "./math.js";
import { sum as plus } from "./math.js";
import * as math from "./math.js"; // every export as one object
export * from "./math.js"; // re-export
// in HTML
<script type="module" src="main.js"></script>Examples
// math.js: export const PI = 3.14;
// export function double(n) { return n * 2; }
// main.js: import { PI, double } from "./math.js";
// An import takes properties of the module's exports object:
const mathExports = { PI: 3.14, double: (n) => n * 2 };
const { PI, double } = mathExports;
double(PI); // → 6.28// An old-school module (before 2015): a function that's called right away.
// Everything inside is private; only what's returned gets out.
const cart = (function () {
const items = [];
return {
add(item) {
items.push(item);
},
count() {
return items.length;
},
};
})();
cart.add("fish");
cart.count(); // → 1
cart.items; // → undefined — like an unexported module variable// How a bundler runs modules: a function per file + a cache
let runs = 0;
const modules = {
"ids.js": (exports) => {
runs += 1;
let last = 0;
exports.next = () => ++last;
},
};
const cache = {};
function load(name) {
if (!cache[name]) {
cache[name] = {};
modules[name](cache[name]);
}
return cache[name];
}
const fromHeader = load("ids.js"); // import { next } from "./ids.js" in header.js
const fromFooter = load("ids.js"); // and the same in footer.js
fromHeader.next();
fromFooter.next(); // → 2 — the counter is shared
runs; // → 1 — the module ran once// cart.js: export function total(items) { … }
// main.js: import { total as cartTotal } from "./cart.js";
// Renaming on import looks like destructuring —
// except import uses `as`, not a colon:
const cartExports = { total: (items) => items.length };
const { total: cartTotal } = cartExports;
cartTotal(["fish", "cream"]); // → 2as renames when names from different modules clashResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
A module is a file loaded as a module: via <script type="module">, via import from another module, or by a bundler. How it differs from a plain script:
- top-level variables do not become global — they're visible in this file only;
- the code is always in strict mode: assigning to an undeclared variable is a
ReferenceError; - a module runs once, on its first import; every importer gets the same exports. A module with an array inside is an object shared by the whole app;
import/exportappear only at the top level of a file, with the path as a string. So the browser and bundlers see every dependency without running the code: that's how preloading and tree shaking work.
An import isn't a copy but a "live" reference to the exporting module's variable: if the module changes an exported let, importers see the new value. Assigning a new value to an import from outside is impossible — TypeError.
Bundlers (webpack, Vite, Rollup) glue modules into one file: each module becomes a function, and import becomes a call that runs the module (once, with a cache) and returns its exports. In older Node code you'll meet a different system — CommonJS: require("./math") and module.exports = { … }.
Traps
How it differs from…
- Closure
Before 2015, modules were built with a closure: a function called right away hides its variables and returns an object of "exports".
import/exportdo the same at the file level — with no wrappers.export defaultA file can have any number of named exports, and their names are the same for everyone. The default export is one per file, and the importer names it.
When to pick something else
Don't split for the sake of splitting: a file per three-line function means forty imports instead of one clear module. Split by meaning (money, cart, interface). And a small one-page script or a sandbox example doesn't need modules at all.
Practice
Lessons where this appears
- The two-thousand-line fileTale · Chapter 24 · Modules: import and export
- Why a bundler, if the browser understands import?Why? · Chapter 24 · Modules: import and export
- The shelter moves houseWorkshop · Chapter 24 · Modules: import and export
- The cat cafe receiptLab · Chapter 24 · Modules: import and export
- The Spaghetti MonsterBoss · Chapter 24 · Modules: import and export
- Building the weather appWorkshop · Chapter 29 · Final project: a weather app