Course progress0%
Course content

Module 1

Module 2

Module 3

Module 4

Module 5

Module 6

Module 7

Module 8

Module 9

Module 10

Module 11

Module 12

Module 13

Module 14

Module 15

Module 16

Module 17

Module 18

45 min

Named Imports and Exports

Run a small multi-file JavaScript program

By the end of this lesson

  • Run a small multi-file JavaScript program
  • Connect imports to explicit public responsibilities

Move from the console to files

Multiple real modules need a file-based environment. For this module and the projects, use a current Node.js LTS installation and a text editor. Node.js is a JavaScript runtime outside the browser. In a terminal, node --version should print its version. If Node is unavailable, use a JavaScript playground that explicitly supports ES modules; keep the same file boundaries.

Create a practice folder. Use .mjs filenames so Node treats them as ES modules without a package configuration. The lesson uses no external packages, DOM or server.

Two files with one dependency

Save this as calculations.mjs:

export function calculateSubtotal(price, quantity) {
  return price * quantity;
}

Save this beside it as main.mjs:

import { calculateSubtotal } from "./calculations.mjs";
const subtotal = calculateSubtotal(20, 3);
console.assert(subtotal === 60);
console.log("Subtotal:", subtotal);

In that folder, run node main.mjs. Expect Subtotal: 60. Relative imports start with ./ or ../; include the filename extension in this Node setup. Braces name the exact exported binding, and spelling and capitalization must match.

Do not paste an import statement into an ordinary browser console and expect the same file resolution. The console exercises and file-based exercises have different entry points.

Guided correction

An import failure may mean the path, filename or export name does not match. Confirm those first. It does not imply the subtotal formula is wrong. A module can export several related functions; unexported names remain implementation details of that module.

Independent lab

Add a formatting.mjs module exporting formatTotal. Import it in main and print its returned label. Then change only the wording in the formatter. Verify the numeric calculation still returns 60.

Correction

The formatter can return a template literal containing the amount. Main calls it with subtotal. The calculation module need not import the formatter. A presentation change should not alter the pricing formula.

Review

Keep a separate practice folder from the portfolio repository. These examples are learner programs, not instructions to modify the site's build configuration. Later projects reuse this same .mjs execution setup.

Lesson complete?

Your progress is saved on this device.