The previous lesson in this module was about the async patterns that let a browser talk to a server. This lesson is about the file system of your project instead: how JavaScript splits one giant program into several small files, and how those files find each other. The last lesson in this module puts the two together by fetching data over the network.
This is the first lesson in the JavaScript Modules, localStorage and Fetch API module, and the next lesson in this module is about "localStorage and sessionStorage Done Right".
ES modules are the official system for that job. A module file uses export to publish values and import to pull them in, and the browser loads the whole group of files for you. The syntax you meet here is exactly the syntax that Node uses, so code written for a browser can move to a server or to a build tool without being rewritten.
Why split a script into separate files at all?
A single app.js file works fine for a page that has two features. It stops working the moment you add a third one. Search, a shopping cart, a theme switcher, and a shared helper all living in one file means that every change you make risks breaking something you did not even touch. Modules give each file one clear job and one named public surface, so your editor can jump to the right place and the browser can cache each file on its own.
The older <script> tag gives you no such promise. Every classic script shares one global scope, so two files that both declare const total collide, and the later file quietly overwrites anything the earlier one put on window. A module gets its own scope instead, and nothing inside it leaks out unless you export it.
How do you tell the browser to load a module?
Add the type="module" attribute to the script tag. That one attribute changes three things at the same time. The file is parsed as a module, it is deferred until the document has finished parsing, and it runs in strict mode with a scope of its own.
<!-- index.html -->
<script type="module" src="./app.js"></script>
<script type="module" src="./analytics.js"></script>
Because module scripts are deferred by default, you can place the tag in the <head> without worrying about the order of the tags. If you prefer to write a module straight inside the page, put the code between the tags. An inline module script runs after the document has been parsed but before the deferred external modules, so keep the order in mind when two of them depend on each other.
Which export form should you use, and how does the import side work?
Named exports are the default choice, because they rename nothing when they are imported. The importer asks for one specific name, so if you rename that name in the source file the import breaks loudly instead of failing quietly.
// math.js
export const PI = 3.14159;
export function area(radius) {
return PI * radius * radius;
}
export function perimeter(radius) {
return 2 * PI * radius;
}
The importer then names exactly what it wants. A live import has no commas and no semicolon at the end of the statement, and that missing semicolon is a common source of syntax errors when you copy code between files.
// app.js
import { area, perimeter } from './math.js';
import { formatMoney } from './money.js';
const r = 3;
console.log(area(r).toFixed(2));
console.log(formatMoney(perimeter(r)));
That prints 28.27 and then $18.85. The two numbers come from math.js, and money.js only formats the second one, which is exactly the point of keeping the two modules separate.
| Form | Written as | Good for |
|---|---|---|
| Named | export function area() {} | Files with several related helpers |
| Default | export default class Cart {} | A file whose main export has one obvious name |
| Renamed import | import { area as circleArea } from './math.js' | Two files that export the same name |
| Namespace import | import * as math from './math.js' | Passing a whole module around as an object |
Imports are hoisted, which means that the module graph is resolved and evaluated before any of the importing file's own statements run. You can write an import at the bottom of a file and it still works. That is a good reason to keep your imports at the top anyway, because a reader should not have to know about hoisting to follow your file.
Why does a changed export show up in the importer?
ES module imports are live bindings rather than snapshots. The importer holds a reference to the exporting module's variable, so when the exporter reassigns it, the importer sees the new value straight away. This is different from the older CommonJS style, where require hands over a copied value.
// counter.js
export let count = 0;
export function bump() {
count += 1;
}
// main.js
import { count, bump } from './counter.js';
console.log(count); // 0
bump();
console.log(count); // 1
The second console.log prints 1 even though the import statement sits at the top of the file. If you had written const count = 0 in the importer instead, then the two numbers would drift apart permanently.
What happens when two modules import each other?
A cycle is legal, and the module system handles it without crashing. The evaluation order decides what each file can use during its own top-level code. Function declarations are hoisted, so a function can call into the other module even though that module has not finished evaluating yet.
// a.js
import { fromB } from './b.js';
export const label = 'A';
export function fromA() { return 'A calling ' + fromB(); }
// b.js
import { label } from './a.js';
export function fromB() { return 'B seeing ' + label; }
// cycle-main.js
import { fromA } from './a.js';
console.log(fromA()); // A calling B seeing A
Reading a const that has not been initialised yet throws a reference error, so keep the top-level code of a module free of cross-module reads, and move that work into functions that you call later.
Why does my module fail to load with no useful error?
Three failures account for most broken module pages, and the browser message is often unhelpful enough that you need to know them in advance.
- Opening the file directly. A page loaded from
file://cannot fetch other files, because the browser treats each local file as its own separate origin. Serve the folder over HTTP instead, withpython -m http.server 8000, and openhttp://localhost:8000. - A missing extension. The path
'./math'does not resolve. Write'./math.js'with the full file name. - A wrong path. A path in an import resolves against the importing file and not against the page. A path that works from
index.htmlcan be wrong fromjs/app.js, where you need'./math.js'instead of'js/math.js'.
What to remember about ES modules
- Each module file has its own scope, and only the exported names are visible to other files.
- Use
type="module"on the script tag, and you get deferral and strict mode for free. - Prefer named exports, because they document the module's public surface and break loudly when a name is renamed.
- Imports are live bindings, so reassigning an exported
letis visible to every importer immediately. - Serve your page over HTTP, because the
file://protocol cannot load module files.
Try it yourself: Create a folder with index.html, math.js, and app.js. Export a function discount(price, percent) from math.js, import it in app.js, and log the result for a price of 1250 at 20 percent. Then change discount so that it returns a rounded number, and run it again without touching app.js. The import picks up the new behaviour because the binding is live. Open the browser console first, because a module error appears there with the file and the line that failed, while a classic script error often does not say anything useful.