Lesson 11 of 199:37 video

JavaScript modules

Why two script files that never mention each other can break each other, and how modules fix it: module scope, export and import, named and default exports, how modules load and run once, live bindings, require and CommonJS in Node, and packages.

In this lesson

  1. 0:00 Intro
  2. 1:11 One shared scope
  3. 2:01 Modules
  4. 2:58 export and import
  5. 5:07 How modules run
  6. 6:31 Node and require
  7. 7:32 Packages
  8. 8:08 Back to the two files
  9. 8:59 Next time

Two files, one for each rocket: Kestrel and Heron. Each keeps its fuel level in a constant called fuel:

// kestrel.js
const fuel = 80;
console.log(`Kestrel: ${fuel}% fuel`);
// heron.js
const fuel = 40;
console.log(`Heron: ${fuel}% fuel`);

Run either file alone, and it works. Now load both on the same page, with one plain script tag each:

<!-- index.html -->
<script src="kestrel.js"></script>
<script src="heron.js"></script>

Open the page and look at the console:

Kestrel: 80% fuel
Uncaught SyntaxError: Identifier 'fuel' has already been declared

The first file prints its fuel. The second never runs. But heron.js declares fuel once. The other fuel is in a different file, and neither file mentions the other. By the end of this lesson you’ll know how one file broke the other, and how modules stop it: export and import, how modules load and run, and what require means when you meet it in older code.

One shared scope

For most of JavaScript’s life, a page loaded its files with one script tag each, and every one of those files shared a single scope. A variable declared outside every function is global, and the whole program can see it. On a page, the whole program means every file on the page.

So both constants landed in one scope, and the second fuel was a duplicate. That error is the lucky case. Give both files a function with the same name, and there’s no error at all:

// kestrel.js
function report() {
  console.log("Kestrel: 80% fuel");
}
// heron.js
function report() {
  console.log("Heron: 40% fuel");
}

The second quietly replaces the first. Call report() anywhere on the page, and you get Heron’s, whichever one you meant:

report();
// Heron: 40% fuel

Every file has to hope that no other file picks the same names. The old workaround was to wrap each file in a function, whose variables are private. const and let at the top of a plain script share the page’s scope without becoming properties of window; var and function declarations land on window too.

Modules

In 2015, JavaScript got an answer of its own: the module, a file that gets a scope of its own. What it declares at the top stays inside it. The two files don’t change. What changes is how the page loads them:

<!-- index.html -->
<script type="module" src="kestrel.js"></script>
<script type="module" src="heron.js"></script>

Reload, and both lines print:

Kestrel: 80% fuel
Heron: 40% fuel

Each file has its own fuel now, and neither can see the other’s. A third module on the page finds no fuel at all, and window.fuel is undefined.

One catch: open the page straight from your disk, as a file:// address, and the browser blocks module files. Chrome’s console says the request was “blocked by CORS policy”, and neither file runs. Modules have to come from a web server, and one running on your own machine is enough. Any local server works, such as python3 -m http.server in the page’s folder, or your editor’s live preview.

Two more things change in a module. It waits for the page: a module script runs after the HTML has been read. And it always runs in strict mode, so assigning to a misspelled name is an error, not a new global:

// kestrel.js, loaded as a module
const fuel = 80;
feul = 60;
console.log(`Kestrel: ${fuel}% fuel`);
// Uncaught ReferenceError: feul is not defined
//     at kestrel.js:2:6

But the privacy works in both directions. Right now these two files can’t share anything, and a program split across files has to share some things, on purpose.

export and import

Here’s a program in two files. The rocket file has a function, launch, and the mission file wants to call it. Two keywords make that work. In the rocket file, export in front of the function marks it as something the file shares. In the mission file, an import line names what it wants in curly braces, then the word from, then the path to the other file:

// rocket.js
const minFuel = 50;

export function launch(ship) {
  if (ship.fuel < minFuel) {
    console.log(`${ship.name} is grounded`);
    return;
  }
  console.log(`${ship.name} lifts off`);
}
// mission.js
import { launch } from "./rocket.js";

const kestrel = { name: "Kestrel", fuel: 80 };
launch(kestrel);
// Kestrel lifts off

console.log(minFuel);
// Uncaught ReferenceError: minFuel is not defined
//     at mission.js:6:13

./ means the same folder, and the .js is part of the path: "./rocket" isn’t found. To run it, load only the mission file, as a module, from a local server:

<!-- index.html -->
<script type="module" src="mission.js"></script>

Everything the rocket file didn’t export stays private. It keeps its fuel rule in a constant, minFuel, and launch can read it. The mission file can’t.

Named exports

A file can export as many names as it likes. The rocket file now exports two functions, and the import line lists both:

// rocket.js, with this function added after launch
export function refuel(ship) {
  ship.fuel = 100;
}
// mission.js
import { launch, refuel } from "./rocket.js";

const heron = { name: "Heron", fuel: 40 };
launch(heron);   // Heron is grounded
refuel(heron);
launch(heron);   // Heron lifts off

Those braces look like destructuring, const { name, fuel } = kestrel;. They aren’t. Nothing is being taken apart. It’s a list of names, and each one has to match an export exactly. JavaScript checks that list while it loads the files, before any of them runs. Ask for a name the rocket file doesn’t export, and the program never starts. Even the line above the import never prints:

// mission.js
console.log("Mission started");
import { launch, refuel, minFuel } from "./rocket.js";
// Uncaught SyntaxError: The requested module './rocket.js'
// does not provide an export named 'minFuel'

If you’d rather take everything, import star, as, and a name you pick. You get one object with every export on it:

// mission.js
import * as rocket from "./rocket.js";

const heron = { name: "Heron", fuel: 40 };
rocket.launch(heron);   // Heron is grounded

Exports can also be listed at the end of a file, export { launch, refuel };, which works the same as writing export in front of each function.

The default export

Some import lines have no braces at all. That’s the second kind of export: the default. A file can mark one thing as its main export, with export default:

// fleet.js
const fleet = [
  { name: "Kestrel", fuel: 80 },
  { name: "Heron", fuel: 40 },
  { name: "Osprey", fuel: 95 },
];

export default fleet;

To import a default, leave out the braces and pick any name you like, because a default isn’t matched by name:

// mission.js
import fleet from "./fleet.js";
import { launch } from "./rocket.js";

for (const ship of fleet) {
  launch(ship);
}
// Kestrel lifts off
// Heron is grounded
// Osprey lifts off

import ships from "./fleet.js" gives the same array. So the braces tell you which kind you’re getting. With braces: a named export, under its exact name. Without braces: the file’s default, under a name you choose. A file can have many named exports, but only one default. Under the hood, the default is an export named default. One line can take both kinds: if the fleet file also exported a size, import fleet, { size } from "./fleet.js"; would bring in both.

How modules run

When you run the mission file, JavaScript doesn’t start at line one. First it reads the file and collects its imports. It loads those files, collects their imports, and keeps going until it has the whole map. Only then does it run them, and a file’s imports always run before the file itself. That’s why the page loads only the mission file, and everything else follows. It’s also why imports are hoisted: wherever you write them in a file, they load first.

Each module also runs just once, however many files import it. Here the mission file and a rescue file both import the rocket file, which counts its launches:

// rocket.js
let launches = 0;

export function launch(ship) {
  launches = launches + 1;
  console.log(`Launch ${launches}: ${ship.name} lifts off`);
}
// rescue.js
import { launch } from "./rocket.js";

export function sendRescue() {
  launch({ name: "Osprey", fuel: 95 });
}
// mission.js
import { launch } from "./rocket.js";
import { sendRescue } from "./rescue.js";

launch({ name: "Kestrel", fuel: 80 });
sendRescue();
// Launch 1: Kestrel lifts off
// Launch 2: Osprey lifts off

The rocket file ran one time, so both files share it: the same launch, and the same count of launches.

To load a module later, while the program runs, call import("./rescue.js") with parentheses. It returns a promise, and a module can await it outside any function.

What you import isn’t a copy, either. Export the count itself, and import it by name:

// rocket.js
export let launches = 0;

export function launch(ship) {
  launches = launches + 1;
  console.log(`${ship.name} lifts off`);
}
// mission.js
import { launches, launch } from "./rocket.js";

console.log(launches);   // 0
launch({ name: "Kestrel", fuel: 80 });
launch({ name: "Osprey", fuel: 95 });
console.log(launches);   // 2

launches = 0;
// Uncaught TypeError: Assignment to constant variable.
//     at mission.js:8:10

The mission file never changed launches. The rocket file did, and the import shows it, because an import is a live link to the variable in the other file. The standard name for it is a live binding. Destructuring an object would have copied the zero and kept it.

The link is read-only, though. Only the file that declares a variable can change it. An imported object can still be changed through its properties, as any const object can.

Node and require

All of this runs in Node as well as in the browser: save the files in one folder and run node mission.js. But Node is older than modules. It arrived in 2009, six years before the language had its own, so it came with a module system called CommonJS, and a lot of Node code still uses it. To share something, a file assigns it to module.exports. To get it, another file calls a function, require, with the path:

// rocket.js
let launches = 0;

function launch(ship) {
  launches = launches + 1;
  console.log(`${ship.name} lifts off`);
}

module.exports = { launch, launches };
// mission.js
const { launch, launches } = require("./rocket.js");

launch({ name: "Kestrel", fuel: 80 });
launch({ name: "Osprey", fuel: 95 });
console.log(launches);   // 0

Save those two files in a folder of their own, with no package.json, and run node mission.js. The idea is the same: every file has its own scope, and chooses what to share. But require is an ordinary function, and it returns an ordinary object. So here the braces really are destructuring, and the count really is a copy: zero, even after two launches.

One file can’t use both systems. Write import in a file that’s loaded the old way, in Node or in a plain script tag, and you get the same message:

SyntaxError: Cannot use import statement outside a module

Node decides file by file. A .mjs file, or a .js file under a package.json that says "type": "module", is a module. A .cjs file, or a .js file under "type": "commonjs", uses require, and npm init writes "type": "commonjs" for you. With neither, current Node reads the file and works it out.

Packages

One more kind of import: a name with no ./ and no path.

// mission.js
import chalk from "chalk";
import { launch } from "./rocket.js";

console.log(chalk.green("Kestrel lifts off"));

That’s a package: code that someone else wrote and published for anyone to import. Most packages are published on npm, and the tool that installs them comes with Node. Run npm install chalk in the folder, and it lands in a folder called node_modules, which is where Node looks up a bare name. Run node mission.js, and the line prints in green. The install also writes a package.json that doesn’t say which system the folder uses, so Node warns that it had to work it out; add "type": "module" to that file and the warning goes.

A browser has no such folder. Hand it a bare name, and it can’t resolve it:

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

So on the web a package usually goes through a build tool first. Without one, a bare name needs an import map or a full URL. We’ll install our first package when we get to Node, later in this series.

Back to the two files

As modules, Kestrel and Heron each keep their own fuel. Now say a third file needs both. Export fuel from each, import both, and the same error is back:

// kestrel.js
export const fuel = 80;
console.log(`Kestrel: ${fuel}% fuel`);
// heron.js
export const fuel = 40;
console.log(`Heron: ${fuel}% fuel`);
// mission.js
import { fuel } from "./kestrel.js";
import { fuel } from "./heron.js";
// Uncaught SyntaxError: Identifier 'fuel' has already been declared

This time it’s fair: two imports with one name, in one file’s scope. But now the clash is in a file you’re writing, and you settle it right on the import line, with as:

// mission.js
import { fuel as kestrelFuel } from "./kestrel.js";
import { fuel as heronFuel } from "./heron.js";

console.log(kestrelFuel + heronFuel);
// Kestrel: 80% fuel
// Heron: 40% fuel
// 120

Two files can use the same name. The file that imports them decides what each one is called. as works on the way out too: export { fuel as kestrelFuel };.

Summary

  • Plain scripts on a page share one scope, so two files can collide over a name, or one can quietly replace the other’s function.
  • A module gives a file a scope of its own. In a browser, load it with <script type="module">, from a server. It always runs in strict mode.
  • export chooses what leaves a module; import names what comes in. Everything else stays private.
  • Named exports are imported in braces, under their exact names, and the names are checked before anything runs. A default export is imported without braces, under any name you choose.
  • JavaScript loads every import first, runs each module once, and shares it with every file that imports it. An import is a live, read-only link to the exported variable.
  • Node also has CommonJS: module.exports and require, an ordinary function that returns an ordinary object. A file uses one system or the other.
  • A name with no ./ is a package, found in node_modules by Node and resolved by a build tool, an import map or a full URL in the browser.
  • Two imports with one name clash; as renames one where it comes in.
Video transcript

Intro

Two files, one for each rocket: Kestrel and Heron. Each keeps its fuel level in a constant called fuel. Run either file alone, and it works. Now load both on the same page. The first prints its fuel: eighty percent. The second never runs. SyntaxError: identifier fuel has already been declared. But this file declares it once. The other fuel is in a different file, and neither file mentions the other. So how did one file break the other? Today, we find out.

By the end of this video, you'll understand three things. One: module scope: why every plain script on a page shares its names with the others, and how a module keeps its own. Two: export and import: how a file shares only what it chooses, and why some imports have curly braces and others don't. Three: how modules load and run, in the browser and in Node, and what require means when you meet it in older code.

One shared scope

Until now, every program in this series fit in one file. Real programs don't. And for most of JavaScript's life, a page loaded its files with one script tag each, and every one of those files shared a single scope. In the functions episode, we said a variable declared outside every function is global, and the whole program can see it. The whole program means every file on the page. So both constants landed in one scope, and the second fuel was a duplicate. That error is the lucky case. Give both files a function with the same name, report, and there's no error at all. The second quietly replaces the first. Call report, and you get Heron's, whichever one you meant. Every file has to hope that no other file picks the same names.

Modules

In 2015, JavaScript got an answer of its own: the module, a file that gets a scope of its own. What it declares at the top stays inside it. The two files don't have to change. What changes is how the page loads them: add type equals module to each script tag. Reload. Kestrel, eighty percent. Heron, forty. Each file has its own fuel now, and neither can see the other's. One catch: open the page straight from your disk, and the browser blocks module files. They have to come from a web server, and one running on your own machine is enough. A module also runs in strict mode, which we met in the errors episode: assign to a misspelled name here, and you get an error, not a new global. But the privacy works in both directions. Right now these two files can't share anything, and a program split across files has to share some things, on purpose.

export and import

Here's a program in two files. The rocket file has a function, launch. The mission file wants to call it. Two keywords make that work. In the rocket file, write export in front of the function. That marks it as something this file shares. In the mission file, an import line names what it wants, in curly braces, then the word from, then the path to the other file. Dot slash means the same folder. Now the mission file can call launch, and Kestrel lifts off. Everything the rocket file didn't export stays private. It keeps its fuel rule in a constant, minFuel, and launch can read it. The mission file can't: minFuel is not defined.

A file can export as many names as it likes. The rocket file now exports two functions, launch and refuel, and the import line lists both. Those braces look like destructuring, from the episode on modern syntax. They aren't. Nothing is being taken apart. It's a list of names, and each one has to match an export exactly. JavaScript checks that list while it loads the files, before any of them runs. Add minFuel to the list, and the program never starts: the rocket file does not provide an export named minFuel. If you'd rather take everything, import star, as, and a name you pick. You get one object with every export on it, and the call becomes rocket dot launch.

Some import lines have no braces at all. That's the second kind of export: the default. A file can mark one thing as its main export, with the words export default. The fleet file does that with its array of three rockets. To import a default, leave out the braces and pick any name you like, because a default isn't matched by name. So the braces tell you which kind you're getting. With braces: a named export, under its exact name. Without braces: the file's default, under a name you choose. A file can have many named exports, but only one default.

How modules run

So what happens when you run the mission file? JavaScript doesn't start at line one. First it reads the file and collects its imports. It loads those files, collects their imports, and keeps going until it has the whole map. Only then does it run them, and a file's imports always run before the file itself. That's why you load only the mission file, and everything else follows. Each module also runs just once, however many files import it. Here the mission file and the rescue file both import the rocket file. It ran one time, so they share it: the same launch, and the same count of launches. Launch one, from the mission file. Launch two, from the rescue file.

What you import isn't a copy, either. Export the count itself, launches, and import it by name. At the start, the mission file prints it: zero. After two launches, it prints the same name again: two. The mission file never changed it. The rocket file did, and the import shows it, because an import is a live link to the variable in the other file. Destructuring an object would have copied the zero and kept it. The link is read-only, though. Assign to launches from the mission file, and you get a TypeError. Only the file that declares a variable can change it.

Node and require

All of this runs in Node as well as in the browser. But Node is older than modules. It arrived in 2009, six years before the language had its own, so it came with a module system called CommonJS, and a lot of Node code still uses it. You'll know it by two names. To share something, a file assigns it to module dot exports. To get it, another file calls a function, require, with the path. The idea is the same: every file has its own scope, and chooses what to share. But require is an ordinary function, and it returns an ordinary object. So here the braces really are destructuring, and the count really is a copy: zero, even after two launches. One file can't use both systems. Write import in a file that's loaded the old way, in Node or in a plain script tag, and you get the same message: cannot use import statement outside a module.

Packages

One more kind of import: a name with no dot slash and no path. That's a package: code that someone else wrote and published for anyone to import. Most packages are published on npm, and the tool that installs them comes with Node. Install one, and it lands in a folder called node modules, which is where Node looks up a bare name. A browser has no such folder. Hand it a bare name, and it can't resolve it, so on the web a package usually goes through a build tool first. We'll install our first package when we get to Node, later in this series.

Back to the two files

Which brings us back to the two files we started with. As modules, each keeps its own fuel. Now say a third file needs both. Export fuel from each, import both, and the same error is back: fuel has already been declared. This time it's fair: two imports with one name, in one file's scope. But now the clash is in a file you're writing, and you settle it right on the import line. Import the first fuel as kestrelFuel, and the second as heronFuel. Eighty plus forty: one hundred twenty. Two files can use the same name. The file that imports them decides what each one is called.

Next time

That's modules in one line: a module gives a file a scope of its own; export chooses what leaves it, import names what comes in, and each module runs once, shared by every file that imports it. Next time, we open up the for of loop: why it walks an array but throws on a plain object, and how to make your own objects work with it, using iterators and generators.

Learn more