ES modules: import and export

A program that grows past one file needs a way to say what a file offers and what it takes from another. The language itself answers with ES modules: export marks what a file gives away, and import names what it takes, with a static list that the engine reads before any code runs.

This lesson uses ES modules, and the reason is the one that decides the question in practice: they are what the language defines and what the browser loads. In Node.js a file becomes an ES module either with the .mjs extension or, as here, because the package.json of the folder says "type": "module". The lesson after this one shows the older system, CommonJS, and the two do not mix inside one file.

A folder of modules

The folder has three files: the manifest that makes every .js in it an ES module, a module with three exports, and a program that imports them. The specifier starts with ./ because a bare name would be a package, and it ends with .js because an ES module import names a file rather than a module id.

The file package.json:

{ "name": "es-module-demo", "version": "1.0.0", "type": "module" }

The file math.js:

export const double = (n) => n * 2; export function square(n) { return n * n; } export default function cube(n) { return n * n * n; }

The file app.js:

import cube, { double, square } from './math.js'; console.log('double 4:', double(4)); console.log('square 4:', square(4)); console.log('cube 4:', cube(4)); console.log('the default import has a name of our choice:', cube.name);

node app.js

double 4: 8
square 4: 16
cube 4: 64
the default import has a name of our choice: cube

The program printed the three results and the name of the default export, which is the name the function was declared with in its own file. double, square and cube were named exports, and the default export is the one that needs no braces. Every binding is read-only: an assignment to an imported name is a SyntaxError, which keeps the module graph honest.

Default and named exports

A module may export one default value and any number of named ones. The default is usually the main thing the module is for, and it is imported without braces under a name the importing file chooses, which is why two files can call it differently. A named export is imported in braces and under its own name, with as for a local alias.

The file stats.js:

export const total = (numbers) => numbers.reduce((sum, n) => sum + n, 0); const average = (numbers) => total(numbers) / numbers.length; export default average;

The file use-default.js:

import average, { total as sum } from './stats.js'; const numbers = [2, 4, 6]; console.log('the total:', sum(numbers)); console.log('the average:', average(numbers)); console.log('the default is a function:', typeof average, average.name);

node use-default.js

the total: 12
the average: 4
the default is a function: function average

The default arrived as average, the name the file chose, and the named export arrived as sum, which is the same binding under a local name. The function name in the third line is the one from stats.js, because a rename changes the binding in the importing file and not the function. A default export is a convenience, and a module that exports several things of equal weight is clearer with named exports only.

Re-exports and a namespace

A module can pass an export on without importing it first: export { double } from "./math.js" puts the name in the public list of a second file. That is how a folder offers one entry point and keeps the internal layout private, and it is also how a default export is renamed on the way through. A namespace import collects every export of a module into one object.

The file index.js:

export { double, square } from './math.js'; export { default as cube } from './math.js';

The file barrel.js:

import { cube, double, square } from './index.js'; import * as math from './math.js'; console.log('double 5:', double(5)); console.log('square 5:', square(5)); console.log('cube 5:', cube(5)); console.log('a namespace has every export:', Object.keys(math).sort().join(',')); console.log('a default sits under its own name:', math.default.name);

node barrel.js

double 5: 10
square 5: 25
cube 5: 125
a namespace has every export: default,double,square
a default sits under its own name: cube

The three names came from one entry point that holds no code of its own, and the namespace object listed the same three names plus the default. A namespace is a read-only view: the keys are the exports, and a name that a module does not export is simply absent. The last line reaches the default through .default, because that is the key a namespace always gives the default, whatever the file called the function.

An export that is not there

An import is checked when the module is linked, before any code runs, so a name that the other file does not export stops the program at once. The file below asks for triple, which math.js does not have, and the second file imports it so the error can be printed as one line instead of a stack trace.

The file wrong.js:

import { triple } from './math.js'; console.log('triple 4:', triple(4));

The file check.js:

try { await import('./wrong.js'); } catch (error) { console.log(error.name + ': ' + error.message); }

node check.js

SyntaxError: The requested module './math.js' does not provide an export named 'triple'

The message names the module and the export, so the fix is one of two: export the function, or import the name that exists. Running the file directly prints the same line after the file name and a caret. Because the check happens at link time, a misspelt import never reaches the code that would have used it, which is the main advantage of using import over a call that loads a file when it runs.

Exercises

  1. Add a named export half to math.js and import it in app.js. Which of the three lines of that file change?
  2. Rename the default import in use-default.js to avg. Does the third line of the output change?
  3. Export the default of math.js from index.js under the name cube without the as keyword. What does the loader say?
  4. Write import math from "./math.js" in app.js and print math.double. What happens, and why?
  5. Remove "type": "module" from package.json and run app.js again. Which error appears first?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What makes the .js files of a folder ES modules in Node.js?

    Answer

    "type": "module" in package.json

    The manifest decides for the whole folder, and the .mjs extension is the alternative for a single file.

  2. How is a default export imported?

    Answer

    Without braces, under a name of the importing file

    The default is a single value, so the importing file chooses the binding name.

  3. What does import * as math from "./math.js" give?

    Answer

    A read-only object with every export of the module

    The namespace object holds the exports, the default under the key default.

  4. When is an import checked against the other file?

    Answer

    At link time, before any code runs

    The module graph is linked first, which is why a missing export is a SyntaxError.

  5. What does this module print? export const double = (n) => n * 2; console.log(double(4));

    Answer

    8

    The export is a declaration like any other, and the call below it runs when the module is evaluated.

  6. What does this module print? const average = (a, b) => (a + b) / 2; export default average; console.log(average(2, 4));

    Answer

    3

    A default export is a value the module offers, and the local code still runs as usual.

  7. What does this module print? console.log(typeof require);

    Answer

    undefined

    An ES module has no require binding, and typeof of an undeclared name is safe and gives undefined.

  8. What does this module print? console.log(typeof import.meta.url);

    Answer

    string

    import.meta is the object a module gets for its own metadata, and its url is a string.

  9. A folder has package.json with "type": "module", and math.js exports double and square. The file app.js contains: import { triple } from "./math.js"; console.log(triple(4)); What happens when app.js runs?

    Answer

    A SyntaxError: the requested module does not provide an export named triple

    The name is checked at link time, so the program stops before the call.

  10. A folder has package.json with "type": "module", and math.js has one default export and no named ones. The file app.js contains: import { cube } from "./math.js"; What happens when app.js runs?

    Answer

    A SyntaxError: the requested module does not provide an export named cube

    A default export is not a named one, and the braces ask for a named export only.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev