Skip to content

ES Modules

The Course
•
17 min study

A file can publish a small interface

An ES module has its own scope. export function totalMinutes(...) makes a function available; import { totalMinutes } from "./totals.js" brings that named export into another module. The braces name exports to import; this is module syntax, not an object being copied. Names must match unless you explicitly rename an import with as.

The relative path starts with ./ for the current directory. Use the .js extension in browser modules. A module runs when it is loaded, so keep reusable modules free of surprise printing or changes to the page. Put startup work in the entry file. Importing a function does not call it.

The multi-file editor below runs main.js. Open totals.js to inspect the exported function, then return to main.js and run it. Its output should be 45 and 0. This is a real module relationship, not a comment pretending to import a file.

Browser modules normally need an HTTP-served page with a script of type=module. Double-clicking local HTML is unreliable for relative module imports. This course's editor supplies the environment. Day 7 provides a downloadable project with a small local server and explicit commands. You do not need to install Node to complete these in-page lessons.

Predict and trace

Write the output before running. Follow the values through each call; if your prediction differs, identify the first step that surprised you.

Predict, then run JavaScript
// A reusable function has no printing side effect.
function totalMinutes(records) {
  let total = 0;

  for (const record of records) {
    total += record.minutes;
  }

  return total;
}

console.log(totalMinutes([{ minutes: 20 }, { minutes: 25 }]));
console.log(totalMinutes([]));
Check your prediction
Text
45
0

The console example shows the function’s behavior. The file tabs below separate its definition from the calls.

Open the file tabs

Two real modules JavaScript
import { totalMinutes } from "./totals.js"; console.log(totalMinutes([{ minutes: 20 }, { minutes: 25 }])); console.log(totalMinutes([])); export function totalMinutes(records) { let total = 0; for (const record of records) { total += record.minutes; } return total; }
Check your prediction
Text
45
0

Editing a file tab changes that file; Run starts main.js. An export is part of the module's public contract, so changing its name requires updating its importers too.

The export forms you will meet

A module can export in a few ways. This course uses named exports, because the importer has to spell the same name and a typo fails loudly:

JavaScript
// totals.js
export function totalMinutes(records) { /* … */ }  // named export of a function
export const MAX_MINUTES = 240;                     // named export of a value

// main.js
import { totalMinutes, MAX_MINUTES } from "./totals.js";
import { totalMinutes as sumMinutes } from "./totals.js";  // same export, local name sumMinutes

as renames an import inside the importing file only; totals.js still calls it totalMinutes. You need it when the importing file already uses that name.

You will also see a default export, export default function (records) { … }, imported without braces under any name you choose: import anything from "./totals.js". Because the importer picks the name, a default import cannot be misspelled, which also means a mismatch goes unnoticed. Libraries use both; stay with named exports in this course's code.

When an import names something the module does not export, the module never runs. Changing main.js above to import totalMinute (no s) stops with:

Text
SyntaxError: The requested module './totals.js' does not provide an export named 'totalMinute'

It is reported as a SyntaxError even though the spelling is fine JavaScript, because imports are checked before any line runs. Try it in the file tabs above, then restore the name. Browsers word the message slightly differently but name the module and the missing export.

Build it yourself

Exercise

Export, import and rename

The project below has totals.js and main.js. Add a function titles(books) to totals.js that returns an array of the books' titles without printing anything, and export it. Then import it in main.js. main.js already has its own variable called titles, so import the function under the name bookTitles. Running main.js should print:

Text
Reading list
45
Notes, The Web
Your working space JavaScript
import { totalMinutes } from "./totals.js"; const books = [ { title: "Notes", minutes: 20 }, { title: "The Web", minutes: 25 } ]; // This file already uses the name titles for something else. const titles = ["Reading list"]; console.log(titles[0]); console.log(totalMinutes(books)); // Import titles from totals.js under the name bookTitles, // then print bookTitles(books).join(", "). export function totalMinutes(records) { let total = 0; for (const record of records) { total += record.minutes; } return total; } // Add and export titles(books) here.
Hint 1: the idea

Two files change. totals.js publishes a new named export; main.js adds that name to its existing import list, renamed because the plain name is already taken in main.js.

Hint 2: a first step

Write titles in totals.js with export in front, using map over the books. Then add titles to the braces in main.js without renaming it and run: the error you get ("already been declared") is the reason for the next change.

Show one solution
Model answer JavaScript
import { totalMinutes, titles as bookTitles } from "./totals.js"; const books = [ { title: "Notes", minutes: 20 }, { title: "The Web", minutes: 25 } ]; // This file already uses the name titles for something else. const titles = ["Reading list"]; console.log(titles[0]); console.log(totalMinutes(books)); console.log(bookTitles(books).join(", ")); export function totalMinutes(records) { let total = 0; for (const record of records) { total += record.minutes; } return total; } export function titles(books) { return books.map(book => book.title); }
Text
Reading list
45
Notes, The Web

export in totals.js makes titles part of that module's interface; without it, main.js stops with "does not provide an export named 'titles'". Importing it plainly would clash with main.js's own const titles ("Identifier 'titles' has already been declared"), so titles as bookTitles gives the function a different local name while totals.js keeps calling it titles. Printing stays in main.js, the entry file, so importing totals.js from anywhere else never produces output.

Explain before moving on

What crosses the module boundary? Why should a calculation module not query a form?

Where asynchronous module examples run

This file-tab editor supports this synchronous import example. It does not support top-level await in its entry file. Use the single-program editors and the async main entry point introduced on Day 3 for asynchronous examples. The Day 6 controller walkthrough combines its source functions for that editor, while the downloaded project runs their normal ES modules in Node or the browser. This is a limit of this practice editor, not a rule forbidding top-level await in ES modules.

Going further

Read MDN’s module guide after working through the examples. Use it as a reference when you meet an unfamiliar option; finishing every reference section is not required for this course.

Was this article helpful?

Your response is saved on this device.