Loading

T5 Modern JavaScript (ES6 and later) · Lesson 4

Modules

Splitting a program into files that cannot clash: why modules exist, named exports and imports, renaming and namespace objects, default exports, what a browser needs to load a module (type="module", a server, the right paths and types), Node's modules, and a sensible way to arrange the files of a project.

  • say why modules prevent the clashes of one shared global scope
  • export names from a file, inline or in a list, and rename them
  • import names, rename them, or take them all as a namespace object
  • write and import a default export, and choose between default and named
  • load modules in a browser and in Node, and read the errors when the path, the type or the name is wrong
  • arrange a project's files with one job each, and gather them with re-exports
About 60 minutesChecked against Node.js on the laptop (the kit runs every code block with it) 22.23.1 (2026-11-06); Google Chrome on the laptop (the kit renders every HTML block in it, and the DevTools step describes its panels) 155 (2026-11-06)Play this lesson's games

The back cover

A program that grows past one file needs a way to share code between files without the files tripping over each other. Modules give each file a scope of its own: it shares only what it exports, and borrows only what it imports.

These pages show why modules exist, and how a file lends names with export and borrows them with import. They show renaming, namespace objects and default exports. They show what a browser and Node need to load modules, and how to arrange a project's files so each has one job.

Before you start

The story: One scroll, two rings

Every clock on the upper floor runs from one long scroll of the Script, thousands of lines long, added to by every apprentice who ever worked here. Years apart, two of them wrote a helper called ring. One rings the north bell; the other plays the noon chimes. Nobody noticed that the second ring had quietly replaced the first.

Since then the north bell plays the chimes' tune, and nothing on the scroll says why.

Master Hakim Verge unrolls a yard of it across the bench. "A scroll that everyone writes on is a notice board with no rules," he says. "Give each clock a drawer of its own, and let each drawer lend out only what it means to lend."

Every program in this path so far has lived in one block or one file. Real programs are thousands of lines long, written by many people over years. Kept in one file, or in many scripts that share one global scope, their names collide, as the scope lesson showed. Modules split a program into files that keep their names to themselves, and share only what they choose.

It builds on these ideas. Each one has a tiny example, so you can check that you remember it.

What you already knowA tiny exampleWhere it comes back
The script element.<script src="app.js"></script>A module is loaded with one, marked type="module".
One global scope for all scripts.Two scripts with let count clash.Modules give each file its own scope.
Strict mode."use strict";Every module is strict.
Relative paths.href="./about.html"An import names a file the same way.
Functions and const.const GST_PERCENT = 18;What a file exports.
Objects with properties.prices.withGstA namespace object holds a file's exports.
Destructuring braces.const { a, b } = obj;Import braces look the same, and differ.
The Network panel.One row for each file the page asks for.Each module is a request.
The Console's red lines.An uncaught error, with its message.Reading module errors.
Running a file with Node.node app.jsNode loads modules too.

By the end of this lesson you will be able to:

  • say why modules prevent the clashes of one shared global scope;
  • export names from a file, inline or in a list, and rename them;
  • import names, rename them, or take them all as a namespace object;
  • write and import a default export, and choose between default and named;
  • load modules in a browser and in Node, and read the errors when the path, the type or the name is wrong;
  • arrange a project's files with one job each, and gather them with re-exports.

How to follow this lesson

A module needs other files and a server, which a block on this page cannot give it. So the module blocks were run by the kit on a small real server, in Chrome, and the notes under each block show the files Chrome asked for and the lines its Console showed. To try them yourself, put the files in one folder and serve it, as the browser section explains. The blocks with a Run button use a module written inside the page, which needs no other file.

In one line

A module is a file with its own scope that shares only what it exports; this lesson shows how files lend and borrow, and what a browser and Node need to load them.

Why modules

At a glance

Two classmates both named Arjun cause no trouble while they sit in different classrooms. Put them in one room, and every call of the name is a puzzle. Ordinary scripts on a page are all in one room.

Every script shares one global scope, so two files that both make a name called total collide, or one replaces the other in silence. A module has a scope of its own: its names stay inside it unless it exports them. Modules are also always strict, so slips become errors.

Take a guess: How did programmers keep names private before JavaScript had modules?

The scene's scroll is not a made-up trouble. Here are two files, written years apart, each with a helper called ring:

north.js

function ring() {
  console.log("north bell: dong");
}

chimes.js

function ring() {
  console.log("chimes: ding ding");
}

A page loads both as ordinary scripts, and then the north clock, at noon, calls ring:

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script src="north.js"></script>
<script src="chimes.js"></script>
<script>
  ring();
</script>

The Console shows

Info     chimes: ding ding

The north clock asked for its bell and got the chimes. There was no error at all. All the ordinary scripts of a page share one global scope, so the second function called ring replaced the first, as a second note pinned over the first on a notice board. Two let names would at least have given a SyntaxError; two function declarations give nothing but the wrong tune.

Module

A JavaScript file loaded as a module, with a scope of its own. Its names are private to it unless it exports them, and it can use other modules' exports only by importing them by name.

Load the same two files as modules, each calling its own ring, and each ring stays in its own file:

north.js

function ring() {
  console.log("north bell: dong");
}

ring();

chimes.js

function ring() {
  console.log("chimes: ding ding");
}

ring();

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="north.js"></script>
<script type="module" src="chimes.js"></script>

The Console shows

Info     north bell: dong
Info     chimes: ding ding

Both rings exist, one in each file, and neither can see the other. The only change was type="module" on each script element.

What else changes in a module

A module's top-level names never reach the global scope, not even a var. And a module is always in strict mode, so its top-level this is undefined:

own.js

var shopName = "Ravi Stores";
console.log(window.shopName, this);

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="own.js"></script>

The Console shows

Info     undefined undefined

As an ordinary script, the same file would print Ravi Stores and the window object, as the scope lesson showed. As a module, the var stays inside the file. Lesson 01's advice to write modern code in strict mode is kept for you in every module.

A module can also be written inside the page itself, in a script element of its own with type="module". Such a module cannot import files on this page, but it follows every other rule of modules, so you can run it here and change it:

<!DOCTYPE html>
<title>Clock Tower</title>
<p id="out"></p>
<script type="module">
  var shopName = "Ravi Stores";
  document.getElementById("out").textContent = `${typeof window.shopName} ${this}`;
</script>

Checked in Chrome

  • the module's var is not on the window, and its top-level this is undefined
Ordinary scriptModule
top-level namesglobal: shared with every scriptprivate to the file
strict modeonly with "use strict"always
top-level thisthe windowundefined
using another file's namesthey are already there, if loaded firstimport them by name

Worked example 1

A page loads two widgets as ordinary scripts: a menu and a chat box. Both keep a click count in a top-level let named clicks, so the second script fails. Make each widget a module, so that each keeps its own count.

What we have: two files with the same top-level name

What we need: both widgets working, each with its own count

The plan: load both files as modules; each file's clicks is then private to it

menu.js

let clicks = 0;
clicks++;
console.log("menu clicks", clicks);

chat.js

let clicks = 0;
clicks += 2;
console.log("chat clicks", clicks);

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="menu.js"></script>
<script type="module" src="chat.js"></script>

The Console shows

Info     menu clicks 1
Info     chat clicks 2

Both run: the menu counts 1 and the chat 2.

Check: Chrome's Console shows both lines and no SyntaxError.

A path that fails: renaming one of them to clicks2. It works until a third widget picks the same name; as modules, no name can collide at all.

When you are stuck: names from two files interfere

If the files are ordinary scripts, they share one global scope: a later name can replace or clash with an earlier one.

Load each file as a module with type="module".

Search every file of the page for the name, in DevTools' Sources panel.

Inside a module, a name is private unless the file exports it.

Your turn

Two ordinary scripts on one page both declare function save(). What happens when a third script calls save()?Tap to reveal
  1. All ordinary scripts share one global scope.
  2. The second declaration replaced the first, with no error.

The second save runs, silently.

In a module, what does a top-level console.log(this) print?Tap to reveal
  1. Modules are always in strict mode.
  2. At the top of a strict module, this is undefined.

undefined.

A module has var theme = "dark"; at its top. What is window.theme on that page?Tap to reveal
  1. A module's top-level names stay in the module, var included.

undefined.

Did you know?

Iffy

Before modules, programmers hid names inside a function that ran at once. On 15 November 2010 Ben Alman proposed a name for the pattern: Immediately-Invoked Function Expression, IIFE for short. Someone suggested the pronunciation iffy, and Alman liked it. Code wrapped in (function () { ... })() kept its names private, the job a module now does by itself.

Why it fits here: It answers this topic's question: before modules, a function that ran at once was the usual way to keep names private.

Source: Ben Alman: Immediately-Invoked Function Expression (IIFE)

require before import

Modules for JavaScript began outside the browser. In January 2009 the Mozilla engineer Kevin Dangoor started a project called ServerJS, renamed CommonJS that August to show its wider use. Its require became, in the words of Node's documentation, the original way to package JavaScript code for Node.js. The standard's own import and export came six years later, with ES2015.

Why it fits here: It explains the two module systems met in Node: require came first, from CommonJS, and the standard's import came later.

Sources: Wikipedia: CommonJS; Node.js documentation: Modules: CommonJS modules; ECMAScript 2015 Language Specification

In one line

Ordinary scripts share one global scope, so their names collide or replace each other in silence. A module has a scope of its own, is always strict, and shares only what it exports.

Exporting: what a file lends

At a glance

A library lends some books and keeps others in a reference room that never leaves the building. A module does the same with its names.

The word export, written before a declaration or in an export list, makes a name public; everything else stays private to the file. Private names cannot be reached from outside at all. The word as renames an export on its way out. And importing a name that a file does not export stops the whole program with a SyntaxError, before any of its code runs.

Take a guess: Can a tool tell which exports nobody uses, and leave them out?

A module keeps everything to itself until it says otherwise. The word export in front of a declaration makes that name available to other modules. Here is a small file of tax rules for the Clock Tower's canteen:

prices.js

export const GST_PERCENT = 18;

export function withGst(price) {
  return round2((price * (100 + GST_PERCENT)) / 100);
}

function round2(n) {
  return Math.round(n * 100) / 100;
}

Two names are exported: the rate and the function that adds it. round2, a helper that rounds to paise, has no export in front of it, so it is private: only code inside prices.js can call it. A module's exports are its public part, like the counter of a shop, and everything else is the back room.

Named export

A name that a module makes available under its own name, by writing export before its declaration, or by listing it in export { ... }. Other modules import it by exactly that name.

Another file uses the function by importing it, and the page loads that file as a module:

main.js

import { withGst } from "./prices.js";

console.log(withGst(100), withGst(99.99));

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="main.js"></script>

The Network panel shows

200  document    /
200  script      /main.js
200  script      /prices.js

The Console shows

Info     118 117.99

Look at the requests. The page named only main.js, and Chrome asked for prices.js on its own, because main.js imports from it. A browser follows the imports from file to file, and asks for every module the program needs.

An export list, and renaming

Instead of marking each declaration, a file can list its exports in one place, usually at the end. A reader then sees the file's whole public part at a glance. In the list, as gives an export a different public name:

prices.js

const GST_PERCENT = 18;

function withGst(price) {
  return (price * (100 + GST_PERCENT)) / 100;
}

export { withGst as addGst, GST_PERCENT };

main.js

import { addGst, GST_PERCENT } from "./prices.js";

console.log(addGst(200), GST_PERCENT);

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="main.js"></script>

The Console shows

Info     236 18

Inside prices.js the function is still called withGst; other files know it only as addGst. ₹200 with 18% GST is ₹236.

Private means private

A file that tries to import a name that was never exported does not get undefined. The whole program is refused before any of it runs, and Chrome names the module and the missing name:

main.js

import { round2 } from "./prices.js";

console.log(round2(2.345));

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="main.js"></script>

The Console shows

Error    Uncaught SyntaxError: The requested module './prices.js' does not provide an export named 'round2'

It is a SyntaxError, although each file is written correctly on its own, because the imports and exports of all the files are matched before the program starts. That is useful: a misspelt import is found at once, not in the middle of a customer's bill.

Worked example 2

The canteen wants a file of fares for its delivery riders: a base fare of ₹20 and ₹8 a kilometre, with a function fare(km). Only fare should be public; the two rates should stay private. Write the file, and use fare from main.js for a 5 km trip.

What we have: two rates and a function that uses them

What we need: a module that exports only fare, and its use

The plan: declare the rates without export, export the function, and import it in main.js

fares.js

const BASE = 20;
const PER_KM = 8;

export function fare(km) {
  return BASE + PER_KM * km;
}

main.js

import { fare } from "./fares.js";

console.log(fare(5));

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="main.js"></script>

The Console shows

Info     60

A 5 km trip costs ₹60.

Check: 20 + 8 × 5 = 60, and no other file can change BASE or PER_KM, because no other file can see them.

A path that fails: exporting the rates too, so that main.js can work the fare out itself. The rule is then written twice, and a change in one place is missed in the other.

When you are stuck: an import says the module does not provide an export

Open the named module and check that the name has export in front of it, or is in its export list.

Check the spelling and capitals: imports match exports exactly.

If the export was renamed with as, import the public name.

Remember that one wrong import stops the whole program, so fix it before looking for other bugs.

Your turn

In prices.js, round2 has no export in front of it. Which code can call it?Tap to reveal
  1. Names without export are private to their module.

Only code inside prices.js.

Write an export list that makes the local function total public under the name sum.Tap to reveal
  1. In an export list, as gives the public name.

export { total as sum };

Why does a misspelt import stop the program before any line runs?Tap to reveal
  1. All imports and exports are matched before the program starts.

Because a module's imports are checked when the files are linked, as a SyntaxError.

Did you know?

Shaking the tree

Because exports are written plainly, tools can read them without running the code. Rollup, a tool that bundles modules into one file, statically analyzes the code you import and excludes anything that is not actually used; its own guide calls this tree shaking. So a module that exports fifty helpers costs a page only the few that it imports.

Why it fits here: It answers this topic's question: since exports are fixed in the code, a tool can see which are never imported and leave them out.

Source: Rollup: README

A package that lends only some files

A whole package can choose what it lends, as a file does. Node's documentation describes the exports field of package.json: once a package defines it, other code cannot reach any entry point that it does not list, not even the package.json itself. Node warns that adding the field to an existing package is likely to break code that used the hidden files.

Why it fits here: It shows this topic's rule one level up: a package, like a file, can keep everything private except what it lists.

Source: Node.js documentation: Modules: Packages

In one line

The word export, before a declaration or in an export list, makes a name public; everything else stays private to the file. The word as renames an export. Importing a name that is not exported stops the whole program with a SyntaxError.

Importing: what a file borrows

At a glance

A borrowed book still belongs to the library, and a reader cannot rewrite its pages. An imported name works the same way.

A line such as import { add } from "./maths.js" borrows a named export, as renames it, and import * as maths takes all the exports as one object. Imported names are read-only live links: if the module changes the value, the importer sees the change. And a module runs only once, however many files import it. Reading the code, you can always tell where a name came from.

Take a guess: Can a module import a JSON file directly, without any extra code?

An import statement names what it borrows, in braces, and the file it borrows from, in quotes. The quoted text is the module specifier: in a browser, the file's address, relative to the importing file. "./prices.js" means prices.js in the same folder; "../lib/prices.js" would go up one folder first.

Import statement

A line at the top of a module, import { a, b } from "./file.js";, that makes the named exports of another module usable in this one. The names must be exported by that module.

A different name, or all of them at once

If a borrowed name clashes with one of your own, or reads badly where you use it, as gives it a local name:

main.js

import { withGst as addTax } from "./prices.js";

console.log(addTax(50));

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="main.js"></script>

The Console shows

Info     59

To borrow everything a module exports, import it as a namespace object: one object whose properties are the module's exports. Private names are not among them:

main.js

import * as prices from "./prices.js";

console.log(prices.GST_PERCENT, prices.withGst(50), typeof prices.round2);

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="main.js"></script>

The Console shows

Info     18 59 undefined

A namespace is handy when a file uses many exports of one module, and it shows at every use where a name comes from: prices.withGst can only be the one from prices.js.

Borrowed, not owned

An imported name cannot be given a new value by the importing file. Only the module that exports it can change it:

main.js

import { GST_PERCENT } from "./prices.js";

GST_PERCENT = 5;

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="main.js"></script>

The Console shows

Error    Uncaught TypeError: Assignment to constant variable.

The message speaks of a constant, because to the importing file an imported name behaves like a const. When the exporting module does change a value, every importer sees the new value, because an import is a live link to the exporter's name, not a copy:

counter.js

export let visits = 0;

export function visit() {
  visits++;
}

main.js

import { visits, visit } from "./counter.js";

console.log(visits);
visit();
visit();
console.log(visits);

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="main.js"></script>

The Console shows

Info     0
Info     2

A module runs once

When two modules import the same module, it is fetched once and run once, and both share its exports. Here north.js and south.js both import bells.js, which prints a line when it runs:

bells.js

console.log("bells.js runs");

export const BELLS = 3;

north.js

import { BELLS } from "./bells.js";

console.log("north sees", BELLS);

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="north.js"></script>
<script type="module" src="south.js"></script>

The Network panel shows

200  document    /
200  script      /north.js
200  script      /south.js
200  script      /bells.js

The Console shows

Info     bells.js runs
Info     north sees 3
Info     south sees 3

south.js is the same as north.js with south in its message. bells.js appears once in the requests and its line once in the Console. That makes a module a good home for something there must be only one of, such as a program's settings.

Import braces are not destructuring

An import's braces look like the object patterns of lesson 03, but they are a list of names, not a pattern. There are no defaults inside them, and a new name is given with as, never with a colon: import { withGst as addTax }, not { withGst: addTax }.

Worked example 3

The Clock Tower's settings live in one module, with the opening hour and a function that changes it for the festival week. The north and south faces both import the hour. Show that a change made through the function is seen by a face that imports the hour.

What we have: a settings module with a let and a function that changes it

What we need: the new hour, seen from another module

The plan: export the let and the function from settings.js, and import both into main.js, printing the hour before and after the change

settings.js

export let openHour = 6;

export function festivalWeek() {
  openHour = 5;
}

main.js

import { openHour, festivalWeek } from "./settings.js";

console.log("opens at", openHour);
festivalWeek();
console.log("opens at", openHour);

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="main.js"></script>

The Console shows

Info     opens at 6
Info     opens at 5

The hour reads 6, then 5 after festivalWeek().

Check: main.js never assigned openHour itself; it saw the change made inside settings.js.

A path that fails: writing openHour = 5; in main.js. An imported name is read-only there, so the program stops with TypeError: Assignment to constant variable.

When you are stuck: an import does not behave as expected

Assignment to constant variable means a file tried to change a name it imported: ask the exporting module to change it, with a function.

A value that changed is seen by every importer, because imports are live links.

Use as to rename, never a colon, and no defaults inside import braces.

Check the specifier: ./ for the same folder, ../ to go up one.

Your turn

Write an import that borrows withGst from ./prices.js and calls it gross in this file.Tap to reveal
  1. as gives a borrowed name a local name.

import { withGst as gross } from "./prices.js";

Two modules import ./bells.js, which prints a line when it runs. How many times is the line printed?Tap to reveal
  1. A module is fetched once and run once, however many modules import it.

Once.

What does import * as prices from "./prices.js"; give, and can it reach round2?Tap to reveal
  1. It gives one object with a property for each export.
  2. round2 is not exported.

A namespace object; prices.round2 is undefined.

Did you know?

JSON by import

A module can now import a JSON file straight into an object: import data from "./data.json" with { type: "json" }. MDN marks import attributes as Baseline 2025, working in the latest browsers since April 2025, and the json type says the file must contain JSON. TC39's list of finished proposals names Import Attributes, by Myles Borins, Sven Sauleau, Dan Clark and Daniel Ehrenberg.

Why it fits here: It answers this topic's question: with an attribute saying the file is JSON, a module imports a data file as an object.

Sources: MDN: Import attributes; TC39: Finished Proposals

An object you cannot change

An import * as maths gives an object, but an unusual one. MDN describes the namespace object as a sealed object with a null prototype: nothing can be added to it, and it has none of the usual object methods. The standard says it exposes the bindings exported from a module, so its properties are live exports that the importer can read but never assign.

Why it fits here: It sharpens this topic's namespace objects: the object stands for the module itself, so it cannot be changed from outside.

Sources: MDN: import; ECMAScript Language Specification: Module Namespace Exotic Objects

In one line

A line such as import { a } from "./file.js" borrows a named export; as renames it, and import * as ns takes them all as one object. Imported names are read-only live links, and a module runs once however many files import it.

Default exports

At a glance

A shop sells many things but is known for one: the sweet shop's rasgulla, the stall's chai. A module can mark one main value in the same way.

The words export default mark it, and it is imported without braces, under any name the importer likes. Named exports are imported in braces, by their exact names. Teams often prefer named exports, because their names are checked: a typo in braces is an error, while a default takes any name, typos included.

Take a guess: Do the style guides of big companies agree on default exports?

Some files exist to give one main thing: a file that formats rupees, a file that holds one widget. Such a file can mark that thing as its default export, and an importer then takes it without braces:

Default export

The one value a module marks with export default. It is imported without braces, import anyName from "./file.js";, under any name the importer chooses. A module can have at most one.

format.js

export const SIGN = "₹";

export default function formatInr(amount) {
  return SIGN + amount.toLocaleString("en-IN");
}

main.js

import formatInr from "./format.js";
import rupees from "./format.js";

console.log(formatInr(125000), rupees(450));

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="main.js"></script>

The Console shows

Info     ₹1,25,000 ₹450

main.js imported the same default twice, once as formatInr and once as rupees, and both work. The name on the importing side is the importer's own choice. The function's name inside format.js does not have to match.

A file can have a default export and named exports together. In the import, the default comes first, without braces, and the named ones follow in braces:

main.js

import formatInr, { SIGN } from "./format.js";

console.log(SIGN, formatInr(2500));

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="main.js"></script>

The Console shows

Info     ₹ ₹2,500

Default or named?

Both work, and real projects use both. The difference is in the names. A named export has one name, used by every file that imports it, so a search for withGst finds every use. A default can be called something different in every file, which is flexible, and makes it harder to follow.

Named exportDefault export
how many in a fileany numberat most one
writtenexport function withGst or export { withGst }export default function formatInr
importedin braces, by its exact name: import { withGst }without braces, by any name: import money
renamed by the importerwith asby writing another name
a misspelt importa SyntaxError that names itno error: any name is accepted

The last row is worth remembering. Misspell a named import and the program refuses to start, naming the mistake. Import a default under a wrong or confusing name and nothing complains. A good habit for your own code is named exports, with a default only where a tool or a framework expects one.

Worked example 4

The canteen's menu module gives one main thing, the list of today's dishes, and also the canteen's name. Write menu.js with the list as its default export and the name as a named export, and print both from main.js.

What we have: a list of dishes and a name

What we need: the dishes as the default, and the name as a named export, used together

The plan: export default the array, export const the name, and import both in one line

menu.js

export const CANTEEN = "Upper Floor Canteen";

export default ["thali", "poha", "chai"];

main.js

import dishes, { CANTEEN } from "./menu.js";

console.log(`${CANTEEN}: ${dishes.join(", ")}`);

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="main.js"></script>

The Console shows

Info     Upper Floor Canteen: thali, poha, chai

It prints Upper Floor Canteen: thali, poha, chai.

Check: the default had no name in menu.js, and main.js called it dishes.

A path that fails: writing the default in braces, import { dishes } from "./menu.js";. Braces ask for a named export called dishes, which menu.js does not have, so the program stops with a SyntaxError.

When you are stuck: a default import does not work

A default is imported without braces; with braces you ask for a named export.

Check that the module really has export default; a module without one has no default to give.

In a mixed import, the default comes first: import main, { other } from ...

If the name you chose is confusing, choose a better one: it is yours.

Your turn

format.js has export default function formatInr. Write an import that calls it money.Tap to reveal
  1. A default is imported without braces, under any name.

import money from "./format.js";

How many default exports can one module have?Tap to reveal
  1. export default marks the one main value.

At most one.

Why does a misspelt named import fail loudly, while a default under any name does not?Tap to reveal
  1. A named import must match an export's name.
  2. A default has no fixed name on the importing side.

Because named imports are matched by name, and a default is not.

Did you know?

Two guides, two answers

Big style guides disagree about defaults. Google's JavaScript style guide says to use named exports in all code and not to use default exports, since importers must give them names, which can lead to inconsistent naming across modules. Airbnb's guide, rule 10.6, says the opposite for a module with a single export: prefer a default export, for readability.

Why it fits here: It answers this topic's question: even large companies split on default exports, which is why this topic gives a reason for its choice.

Sources: Google JavaScript Style Guide; Airbnb JavaScript Style Guide

default is just a name

The words export default are a shortcut for a name. MDN shows export { myFunction as default }, an ordinary named export whose name is default, and the standard gives every default export the name default. MDN adds that in a namespace object the default export is a key called default. So import { default as clock } works too.

Why it fits here: It explains how this topic's braces-free import works: it borrows the export that is named default.

Sources: MDN: export; MDN: import; ECMAScript Language Specification: Static Semantics: ExportedNames

In one line

The words export default mark a module's one main value, imported without braces under any name; named exports are imported in braces by their exact name. Prefer named exports, as their names are checked.

Loading modules in a browser and in Node

At a glance

A browser does not treat every script as a module. It must be told, and the module must come from somewhere it trusts.

A page loads a module with <script type="module">, from a real server that labels the file as JavaScript; opened straight from the disk, it fails. Its specifiers must start with ./ or ../ and name the file in full, .js included. Modules wait for the page, as defer does. Node treats .mjs files, or .js files in a package with type module, as modules.

Take a guess: How can a page make a bare name such as confetti work in an import?

A module needs three things from a browser: to be told it is a module, to be served from a real server, and paths it can follow. Each one, when missing, has its own message.

Told it is a module

Without type="module", a file is loaded as an ordinary script, and ordinary scripts may not use import:

main.js

import { withGst } from "./prices.js";

console.log(withGst(100), withGst(99.99));

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script src="main.js"></script>

The Network panel shows

200  document    /
200  script      /main.js

The Console shows

Error    Uncaught SyntaxError: Cannot use import statement outside a module

prices.js was never asked for: the browser gave up on main.js at its first line. When you see this message, look at the script element, not at the file.

A module script also waits. The browser reads the whole page first and runs modules after, in the order of their script elements, as if each had the defer attribute. So a module in the head can find elements written below it:

clock.js

const panel = document.getElementById("time");
panel.textContent = "12.00";
console.log(panel.textContent);

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="clock.js"></script>
<p id="time">--.--</p>

The Console shows

Info     12.00

The same rule holds for a module written inside the page. Run this one, then the ordinary script under it, which stands in the same place:

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module">
  document.getElementById("time").textContent = "12.00";
</script>
<p id="time">--.--</p>

Checked in Chrome

  • the module ran after the page was read, and found the panel
<!DOCTYPE html>
<title>Clock Tower</title>
<script>
  document.getElementById("time").textContent = "12.00";
</script>
<p id="time">--.--</p>

Checked in Chrome

  • the ordinary script ran before the panel existed, so the panel still shows --.--

The Console shows

Error    Uncaught TypeError: Cannot set properties of null (setting 'textContent')

The ordinary script ran the moment it was read, before the p element existed, found null, and failed. The module waited.

Paths it can follow

In a browser, a module specifier is an address. It must start with ./, ../ or /, or be a full address such as https://... . A bare name is refused before anything is asked for:

main.js

import { withGst } from "prices.js";

console.log(withGst(100));

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="main.js"></script>

The Network panel shows

200  document    /
200  script      /main.js

The Console shows

Error    Uncaught TypeError: Failed to resolve module specifier "prices.js". Relative references must start with either "/", "./", or "../".

Bare names, such as react, are what the Node.js and React steps use: there, a tool or an import map, a small table in the page, turns each bare name into an address. Until then, start every specifier with ./ or ../, and write the file's full name, .js included. A misspelt file name is asked for and not found:

main.js

import { withGst } from "./price.js";

console.log(withGst(100));

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="main.js"></script>

The Network panel shows

200  document    /
200  script      /main.js
404  script      /price.js

The Console shows

Error    Failed to load resource: the server responded with a status of 404 (Not Found)

The Network panel's red 404 row names the missing file. Here it is price.js, one letter short of the real prices.js.

Served from a real server, with the right type

Open a page with modules straight from a file, with an address starting file://, and its modules do not load. MDN's page on modules gives the reason: module requests use the same checks as requests to other sites, and a file address never passes them. So serve the folder, even on your own computer, with a small local server.

The server must also label each module as JavaScript, with the content-type text/javascript. A module labelled as anything else is refused, even though it arrived:

main.js

import { withGst } from "./prices.txt";

console.log(withGst(100));

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="main.js"></script>

The Network panel shows

200  document    /
200  script      /main.js
200  script      /prices.txt

The Console shows

Error    Failed to load module script: Expected a JavaScript-or-Wasm module script but the server responded with a MIME type of "text/plain". Strict MIME type checking is enforced for module scripts per HTML spec.

The row is 200, so the file came; the Console says why it was not used. The kit's server labels a file by its ending, so prices.txt went out as text/plain. Name modules .js, and when one is refused, open its row in the Network panel and read its content-type, as MDN advises.

Modules in Node

Node runs the same import and export. Node's documentation says it treats a file as a module when its name ends in .mjs, or ends in .js inside a project whose package.json says "type": "module". Here are the canteen's two files, renamed .mjs, run in a terminal:

main.mjs

import { withGst } from "./prices.mjs";

console.log(withGst(100), withGst(99.99));

Terminal

/home/asha/shop$ node main.mjs
118 117.99

Node also has an older module system of its own, called CommonJS, with require() and module.exports. You will meet it in older Node code; the Node.js step explains it. Node, like the browser, needs the file's ending in a relative specifier: "./prices.mjs", not "./prices".

MessageWhat is wrongFix
SyntaxError: Cannot use import statement outside a modulethe script element has no type="module"add it
TypeError: Failed to resolve module specifiera bare name such as prices.jsstart with ./ or ../
a 404 row for a .js filea misspelt file or folder, or a missing .jsmatch the real file's name
Failed to load module script: ... MIME typethe server's label is not JavaScriptserve modules as .js, as text/javascript
nothing loads from a file:// pagemodules need a serverserve the folder

Worked example 5

A student's page shows the time on a panel, from clock.js, but the panel stays at --.-- and the Console says Cannot use import statement outside a module. clock.js imports the hour format from ./format.js. Find the fix.

What we have: the Console's message and the page's script element

What we need: the panel showing the time

The plan: the message says the file was loaded as an ordinary script, so the script element is missing type="module"

the page's script element, before

<script src="clock.js"></script>

after

<script type="module" src="clock.js"></script>
  1. With the type, the file is a module, its import works, and, as a module waits for the page, it finds the panel below it.

Add type="module" to the script element.

Check: the message named import, which only a module may use.

A path that fails: moving the import's code into clock.js by hand, to avoid the import. It works for one file, and throws away the reason modules exist.

When you are stuck: a module does not load

Read the Console's red line: each cause has its own message, as the table shows.

Open the Network panel: a missing request means the browser gave up earlier; a 404 is a wrong name; a 200 that was refused is the wrong type.

Check that the page comes from a server, not from file://.

In Node, check the file's ending (.mjs) or the package.json type.

Your turn

What is wrong with import { a } from "utils.js"; in a browser?Tap to reveal
  1. A browser treats a specifier as an address.
  2. It must start with ./, ../ or /, or be a full address.

It is a bare name; write "./utils.js".

A module in the head uses document.getElementById for an element further down. Does it find it?Tap to reveal
  1. Modules run after the whole page has been read.

Yes: modules are deferred.

How do you tell Node that app.js is a module?Tap to reveal
  1. Node looks at the file's ending and at package.json.

Name it app.mjs, or set "type": "module" in package.json.

Did you know?

Bare names with an import map

A page can teach the browser what a bare name means. An import map is a JSON object, in a script with the type importmap, that controls how the browser resolves module specifiers. It can say that confetti means a file at a certain address. MDN shows import maps working across browsers since March 2023, and the HTML standard defines them.

Why it fits here: It answers this topic's question: an import map lets a page use bare names, by saying which file each name means.

Sources: MDN: script type="importmap"; WHATWG: HTML Standard, import maps

A script for old browsers

Pages once shipped two versions of their code. A script with the nomodule attribute runs only in browsers that do not support modules, so it can carry a fallback for older browsers. The HTML standard explains the pair: module scripts run in modern browsers, and classic scripts with nomodule run in older ones, while each browser skips the other.

Why it fits here: It shows how this topic's type="module" was rolled out: old browsers ignored it, and nomodule gave them something else to run.

Sources: MDN: script; WHATWG: HTML Standard, the script element

In one line

A browser needs type="module", a real server that labels modules as JavaScript, and specifiers that start with ./ or ../ and name the file in full. Modules wait for the page. Node treats .mjs files, or .js with type module, as modules.

Arranging a project's files

At a glance

A kitchen keeps spices in one box, pans on one shelf and plates in one rack, so anything can be found in a moment. A project's files can be arranged the same way.

Give each file one job, and export only what other files use. A file can gather many others behind one name with export ... from. Imports are done before a module's own code runs, so write them at the top. And import() loads a module later, only when it is needed.

Take a guess: Can a file that only re-exports other files slow a page down?

Modules are only as helpful as the way the files are cut. The usual rule is one job for each file, named after its job. The canteen's program, so far, has three:

FileIts one jobExports
prices.jsthe tax rulesGST_PERCENT, withGst
format.jswriting amounts for peopleformatInr (default), SIGN
main.jswhat this page doesnothing: it only imports

A file whose job you cannot say in a few words is doing two jobs. A file that imports from ten others is often doing the work that belongs in them.

One door for many files

As a project grows, a page may need things from many small files. A module can gather them and pass them on, with export ... from, which re-exports another module's exports without using them itself:

shop.js

export { withGst, GST_PERCENT } from "./prices.js";
export { default as formatInr } from "./format.js";

main.js

import { withGst, formatInr } from "./shop.js";

console.log(formatInr(withGst(1000)));

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="main.js"></script>

The Network panel shows

200  document    /
200  script      /main.js
200  script      /shop.js
200  script      /prices.js
200  script      /format.js

The Console shows

Info     ₹1,180

main.js knows one address, ./shop.js, and Chrome still asked for all four files. The second line of shop.js passes on format.js's default under a name, formatInr, as default as formatInr. ₹1,000 with 18% GST is ₹1,180.

Imports come first

A module's imports are all done before its own code starts, wherever in the file they are written. An import can also name a module only for what it does when it runs, with no names at all:

setup.js

console.log("setup.js runs");

main.js

console.log("main.js starts");

import "./setup.js";

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="main.js"></script>

The Console shows

Info     setup.js runs
Info     main.js starts

main.js's first line printed second: setup.js ran first, because the import was done before main.js's own code. MDN calls this hoisting, as for function declarations. To keep files honest, write every import at the top, where a reader expects them and where they take effect anyway.

Loading a module later

A module can also be loaded only when it is needed, with import("./charts.js"), written like a function call. It gives a promise, a value that arrives later, and lesson 08 of this step shows it in use.

Worked example 6

The Clock Tower's scroll is cut into modules. The north clock and the chimes each keep a private helper called ring, in a folder called clocks, and each exports one function for noon. Write the two clock files and a main.js that rings both at noon.

What we have: two clocks with a helper of the same name

What we need: both clocks ringing their own tune at noon

The plan: put each clock in clocks/ with ring private and one export each; main.js imports from ./clocks/ and calls both

clocks/north.js

function ring() {
  return "north bell: dong";
}

export function northNoon() {
  return ring();
}

clocks/chimes.js

function ring() {
  return "chimes: ding ding";
}

export function chimesNoon() {
  return ring();
}

main.js

import { northNoon } from "./clocks/north.js";
import { chimesNoon } from "./clocks/chimes.js";

console.log(northNoon());
console.log(chimesNoon());

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="main.js"></script>

The Network panel shows

200  document    /
200  script      /main.js
200  script      /clocks/north.js
200  script      /clocks/chimes.js

The Console shows

Info     north bell: dong
Info     chimes: ding ding

At noon the north bell rings dong and the chimes play ding ding.

Check: each ring stayed private to its file, so neither replaced the other.

A path that fails: exporting both helpers as ring. main.js then needs as to tell the two apart, and every file that uses them must remember which ring is which; kept private, they never meet.

When you are stuck: a project's files are hard to follow

Say each file's job in a few words; split the files that need more.

Keep helpers private, and export only what other files use.

Gather many small files behind one with export ... from, when a page needs many of them.

Write imports at the top: they are done first anyway.

Your turn

Write a line for shop.js that passes on withGst from ./prices.js.Tap to reveal
  1. export ... from re-exports without importing.

export { withGst } from "./prices.js";

main.js prints a line, then imports ./setup.js, which prints too. Which line comes first?Tap to reveal
  1. Imports are done before the module's own code.

setup.js's line.

How do you pass on format.js's default export as formatInr in a re-export?Tap to reveal
  1. The default's export name is default.

export { default as formatInr } from "./format.js";

Did you know?

The cost of a barrel

A file that only re-exports others is called a barrel file, and it has a cost. Vite's guide explains that importing one function through a barrel makes the browser load every file behind it, more files than the page needs, so the page loads more slowly. Its advice is to avoid barrel files where possible, and import what you need from its own file.

Why it fits here: It answers this topic's question: export ... from is handy, but a barrel can make a page load files it never uses.

Source: Vite: Performance

Loading later, since 2020

A page can load a module only when it is needed, such as when a button is pressed. MDN calls import() a function-like expression that loads a module asynchronously; its promise fulfils to a module namespace object. TC39's list of finished proposals names import(), by Domenic Denicola, and the standard's 2020 edition defines it as an ImportCall.

Why it fits here: It dates this topic's import(): loading a module on demand became standard JavaScript in 2020.

Sources: MDN: import(); TC39: Finished Proposals; ECMAScript 2020 Language Specification

In one line

Give each file one job and export only what others use. export ... from gathers many files behind one. Imports are done before a module's own code, so write them at the top; import() loads a module later.

Where it is used

Almost every program written today is made of modules. Here is where each idea of this lesson does its work.

What you learnedWhere it is usedA real example
a scope for each filepages that load code from many teamsa chat widget whose names cannot clash with the shop's
named exports and importsevery modern projectimport { withGst } from "./prices.js";
default exportsone main thing per file, often where a framework expects ita file that holds one page of an app
type="module" and specifiersevery page that loads modules itself<script type="module" src="main.js">
Node's .mjs and type moduleservers and tools written in JavaScriptthe Node.js step's first programs
re-exportslibraries with one front doora shop.js that gathers prices.js and format.js

Mistakes and debugging

These are the slips that people meet most often with modules. Every message below is the real one, from Chrome's Console.

1. A default imported in braces

main.js

import { formatInr } from "./format.js";

console.log(formatInr(450));

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="main.js"></script>

The Console shows

Error    Uncaught SyntaxError: The requested module './format.js' does not provide an export named 'formatInr'

formatInr is format.js's default, which has no name outside the file. The fix: import formatInr from "./format.js";, without braces.

2. The file's ending left out

main.js

import { withGst } from "./prices";

console.log(withGst(100));

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="main.js"></script>

The Network panel shows

200  document    /
200  script      /main.js
404  script      /prices

The Console shows

Error    Failed to load resource: the server responded with a status of 404 (Not Found)

A browser asks for exactly the address written; there is no file called prices. The fix: "./prices.js".

3. A module's name used from an ordinary script

greet.js

export function greet() {
  return "Namaste";
}

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="greet.js"></script>
<script>
  console.log(greet());
</script>

The Console shows

Error    Uncaught ReferenceError: greet is not defined

A module's names are never global, exported or not. The fix: use greet from another module, which imports it.

4. A rename written with a colon

main.js

import { withGst: addTax } from "./prices.js";

console.log(addTax(100));

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="main.js"></script>

The Console shows

Error    Uncaught SyntaxError: Unexpected token ':'

Import braces are not a pattern. The fix: { withGst as addTax }.

5. Two defaults in one file

format.js

export default function formatInr(amount) {
  return "₹" + amount;
}

export default function formatUsd(amount) {
  return "$" + amount;
}

On a real site, served with the files above

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="format.js"></script>

The Console shows

Error    Uncaught SyntaxError: Duplicate export of 'default'

The fix: keep one default, and make the other a named export.

The debugging corner: follow the requests

When a program of modules will not start, open the Network panel and reload. The rows show how far the browser got: each import it followed is a row, the first 404 or refused file is where it stopped, and a missing row means the file before it had an error. Then read the Console's red line, which names the module.

Quick card

The whole lesson on one card. Come back to it whenever you need a reminder.

prices.js: named exports, and a private helper

export const GST_PERCENT = 18;

export function withGst(price) {
  return round2((price * (100 + GST_PERCENT)) / 100);
}

function round2(n) {
  return Math.round(n * 100) / 100;
}

format.js: a default and a named export

export const SIGN = "₹";

export default function formatInr(amount) {
  return SIGN + amount.toLocaleString("en-IN");
}

main.js: named, renamed, default and namespace imports

import { withGst as addTax, GST_PERCENT } from "./prices.js";
import formatInr, { SIGN } from "./format.js";
import * as prices from "./prices.js";

console.log(formatInr(addTax(1000)), GST_PERCENT, SIGN, typeof prices.round2);

The page, served: type="module" on the first file

<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="main.js"></script>

The Network panel shows

200  document    /
200  script      /main.js
200  script      /prices.js
200  script      /format.js

The Console shows

Info     ₹1,180 18 ₹ undefined
When you seeIt meansLook at
SyntaxError: Cannot use import statement outside a modulethe file was loaded as an ordinary scripttype="module" on the script element
SyntaxError: The requested module ... does not provide an export named ...the name is not exported, is misspelt, or is a defaultthe module's exports; braces or none
TypeError: Failed to resolve module specifiera bare namestart with ./ or ../
a 404 row for a modulea misspelt file or a missing .jsthe exact file name
Failed to load module script ... MIME typethe server's label is not JavaScriptthe file's ending and the server
TypeError: Assignment to constant variable.a file changed a name it importeda function in the exporting module
ReferenceError: ... is not defined from an ordinary scripta module's name used outside itimport it in a module

The story: A drawer for each clock

You cut the scroll into files, one for each clock, and mark every file as a module. Inside its own file, each ring is private, and can no longer replace the other. Each file names what it lends to the others, and each clock names what it borrows, and from which file.

At noon the north bell rings its own pattern, and the chimes play theirs.

Master Verge labels the drawers in his careful hand. "Now when a clock goes wrong," he says, "you know which drawer to open, and who borrowed from it."

Reagents gathered: module, export, import, default export, module specifier, type="module".

Sources