By the end of this lesson
Use named exports and relative .mjs imports.
Before you start
- Node.js 24 with a terminal and plain-text editor; the browser-only lesson is labelled separately.
- Complete lesson 15 or be comfortable with its examples.
Three words to know
- Module
- A source file with its own scope and explicit imports and exports.
- Export
- A name made available to another module.
- Relative import
- A module path resolved from the importing module’s location.
1. Export one useful rule
Save this source as totals.mjs. The exported function is available to another module; simply defining it does not call it. Module top-level statements still run when imported, so avoid unrelated CLI work there.
reduce carries an accumulated value through the array. Its callback receives the previous total and the current size, then returns their sum. The final argument 0 is the starting total and also makes an empty list return zero.
export function totalPages(sizes) {
return sizes.reduce((total, size) => total + size, 0);
}
2. Import from the same practice folder
Save the next file as lesson.mjs beside totals.mjs. In Node modules, include ./ for a neighbouring file and include its extension. The path is relative to this source file, while a later relative data-file path is usually relative to the process’s working folder.
import { totalPages } from "./totals.mjs";
console.log(totalPages([2, 3, 1]));
What you should see · example output
6
3. Avoid accidental format changes
This course consistently uses .mjs and import/export. Node also supports CommonJS with require, but you should not casually mix its assumptions into these examples. A package.json type field can change how .js is interpreted; explicit .mjs filenames keep that decision visible for this route.
YOUR TURN
A small check before you continue
If lesson.mjs imports ./totals.mjs, can you rename the other file to totals.js without updating anything?
Show a suggested answer
No. The specified path must exist. File extensions and module format are part of the interface, so update the import and understand the package settings before renaming.
Sources and scope
Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.
