ES modules: import and export

14 min read javascript
Course contents (16 lessons)
  1. Modern syntax
  2. Destructuring, spread and rest
  3. ES modules: import and export
  4. Objects, this and errors
  5. Classes and prototypes
  6. Understanding this in JavaScript
  7. Error handling: try, catch and custom errors
  8. Asynchronous JavaScript
  9. The event loop: how JavaScript handles waiting
  10. From callbacks to promises to async/await
  11. Fetch and REST APIs
  12. Working in the browser
  13. Local storage and session storage
  14. Debugging with browser DevTools
  15. Performance basics: debounce and throttle
  16. Node.js essentials
  17. Node.js and npm basics
  18. Working with files in Node.js
  19. A tiny HTTP server with Node.js
  20. Testing and the final project
  21. Testing basics with the Node.js test runner
  22. Final project: a post explorer with modules and fetch

Why modules

A small script can live in one file. A real project cannot. Once a file grows past a few hundred lines, it is hard to find things, and every function lives in the same global space. Modules fix both problems. Each file has its own scope, and you choose exactly what to share with other files.

Modern JavaScript has a built-in module system, called ES modules or ESM. It uses the import and export keywords.

Named exports

Put export in front of anything you want other files to use.

// math.js
export const PI = 3.14159;

export function add(a, b) {
  return a + b;
}

export function circleArea(radius) {
  return PI * radius * radius;
}

function secret() {
  // not exported, only visible in this file
}

Another file imports them by name, inside curly braces:

// app.js
import { add, circleArea } from "./math.js";

console.log(add(2, 3));          // 5
console.log(circleArea(10));     // 314.159

The names must match what was exported. You can rename on import with as:

import { add as sum } from "./math.js";

You can also import everything into one object:

import * as math from "./math.js";
console.log(math.add(1, 2));

Default exports

A file can have one default export. You import it without braces, and you can call it anything.

// logger.js
export default function log(message) {
  console.log(`[${new Date().toISOString()}] ${message}`);
}
// app.js
import log from "./logger.js";
log("Started");

My preference is named exports. With a default export, every file can pick a different name for the same thing, which makes searching the code harder. Named exports keep one name everywhere, and editors can auto-import them. Many teams ban default exports for that reason. Use whichever your project uses, but be consistent.

Using modules in the browser

Tell the browser that your script is a module with type="module":

<script type="module" src="app.js"></script>

This changes a few things:

  • You can use import and export in the file.
  • The script is deferred automatically, so it runs after the HTML is parsed. You can place it in the head.
  • Module code runs in strict mode.
  • Variables are local to the module. They do not become globals on window.
  • The path in import must be a real path with the file extension: "./math.js", not "./math".
  • You must serve the files over HTTP. Opening index.html by double-clicking (a file:// address) blocks modules in most browsers. Use Live Server, or npx serve in the folder.

Using modules in Node.js

Node supports ES modules too. There are two ways to turn them on:

  • Name the file .mjs.
  • Or add "type": "module" to the nearest package.json. Then .js files are modules.
{
  "name": "demo",
  "type": "module"
}

Older Node code uses CommonJS: const fs = require("fs") and module.exports = .... You will see this in older packages and tutorials. The two systems can be mixed, but it is a topic with sharp edges. For new code, choose ESM and stay with it. Node built-ins are imported with the node: prefix, for example import fs from "node:fs".

Re-exporting and index files

To give a folder one clear entry point, create an index.js that re-exports from the others:

// utils/index.js
export { add, circleArea } from "./math.js";
export { default as log } from "./logger.js";

Now other code can write import { add, log } from "./utils/index.js".

Dynamic import

A regular import is at the top of a file and loaded up front. If you only need a module sometimes, load it on demand with import(), which returns a promise:

button.addEventListener("click", async () => {
  const { drawChart } = await import("./chart.js");
  drawChart();
});

The chart code is downloaded only when the user clicks. This helps page speed for features that most visitors never use. We will explain async and await in a later lesson.

Modules run once

If ten files import the same module, the browser loads and runs it only once. Everybody gets the same instance. That means a module can hold shared state, such as a settings object, and all importers see the same data. Use it with care, since shared mutable state is also a good source of confusing bugs.

Common mistakes

  • Forgetting the file extension. import x from "./math" fails in the browser and in Node ESM. Write ./math.js.
  • Opening the page from the file system. Module scripts need a server.
  • Mixing up default and named imports. import { log } from "./logger.js" fails if log is a default export.
  • Circular imports. If a.js imports b.js and b.js imports a.js, you can get undefined values. Move the shared code into a third file.
  • **Forgetting type="module".** You will see "Cannot use import statement outside a module".

Try it yourself

  1. Create math.js with add and multiply as named exports, and import them in app.js.
  2. Run it in the browser with <script type="module"> and a local server.
  3. Create a package.json with "type": "module" and run node app.js in Node.
  4. Add a default export greet to another file and import it using a different name.
javascript
// math.js
export const PI = 3.14159;

export function add(a, b) {
  return a + b;
}

export function circleArea(radius) {
  return PI * radius * radius;
}

function secret() {
  // not exported, only visible in this file
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account