The two-thousand-line file
export and import, the default export, renaming, module scope, project structure.
app.js, two thousand lines long. Yesterday I added a count variable for the cart — and broke the like counter at the other end of the file. It had a count too. Time to clean out this junk closet.A module is just a file with its own variables. Everything declared in it is visible only inside by default. The module itself decides what to share with other files — with export. Another file takes what it needs with import:
- in
math.js:export function sum(a, b) { return a + b; } - in
main.js:import { sum } from "./math.js";— and then an ordinary call,sum(2, 3).
These are named exports: each has a name, and you write it in curly braces on import exactly the same way. You can export right at the declaration (export const PI = 3.14;) or as a list at the end of the file: export { sum, PI };. The path starts with ./ — "next to me" — and in the browser it includes the .js extension.
There's also the default export — one per file, for the module's "main thing": export default function formatPrice(n) { … }. It's imported without braces, and the importer picks the name: import formatPrice from "./money.js"; or even import price from "./money.js";. You can mix both: import formatPrice, { sum } from "./money.js";.
Names can be changed. If two modules both export total, rename one on import: import { total as cartTotal } from "./cart.js";. You can rename on export too: export { sum as add };. And if you need everything at once, take the module whole, as an object: import * as math from "./math.js"; — then write math.sum(2, 3), math.PI.
// import { total as cartTotal } looks like destructuring with a rename:
const cartModule = { total: (items) => items.length };
const { total: cartTotal } = cartModule;
console.log(cartTotal(["fish", "cream"]));import uses as while destructuring uses a colon. Don't mix them: import { total: cartTotal } is a syntax error.The best gift of modules is their own scope. Scripts loaded with <script src> used to share one global scope: count in one file overwrote count in another. In a module, top-level variables are visible to that file only. That's exactly how my like counter broke. Before 2015, when import/export arrived in the language, people faked modules with a closure — a function that's called right away:
// An old-school "module": everything inside is private,
// only what it returns gets out
const cart = (function () {
const items = [];
function add(item) {
items.push(item);
}
function count() {
return items.length;
}
return { add, count };
})();
cart.add("fish");
cart.add("cream");
console.log(cart.count());
console.log(cart.items);items can't be seen from outside — just like a top-level variable in a real module that wasn't exported.Two more module rules:
- a module runs once, on its first import. Import
cart.jsfrom ten files — its code runs once, and everyone gets the very same exports. So a module with an array inside is one cart shared by the whole app; - module code always runs in strict mode (no need to write
"use strict"). A typo in a variable name won't quietly create a global variable — it throws:
function moduleCode() {
"use strict"; // in a module this line is always implied
try {
totl = 100; // typo: meant total
} catch (err) {
console.log(err.name + ": " + err.message);
}
}
moduleCode();totl = 100 would silently create a global variable — and the bug could live for years.How a real project is laid out:
utils/— small helpers with no side effects: formatting, dates, numbers;api/— everything that talks to the server with fetch;ui/— whatever draws the page;main.js— the entry point: imports the rest and starts the program.
A folder often has an index.js that re-exports its contents: export { default as card } from "./card.js"; or export * from "./format.js";. Then the outside world writes one import from the folder instead of five from different files.
In the browser, a module is loaded like this: <script type="module" src="main.js"></script>. Without type="module" the browser says Cannot use import statement outside a module. Opening such a page with a double click (file://) won't work either — modules load only from a server, even a local one.
And in older Node code you'll meet a different system — CommonJS: const fs = require("fs"); and module.exports = { sum };. It's older than import and still lives in millions of packages. Same idea, different syntax.
app.js into twenty files. Now the cart has its own count, the likes have theirs, and they don't even know about each other. Like cats in different rooms: peace and quiet.Pop quiz
Mistakes are fine: keep trying until you find the right answer, and Byte explains why it's right.