Skip to content
Tutorials Center
My learning

Topics

Lesson 77 of 156 ยท Modules and Tooling

Modules: import and export

Split JavaScript into modules with import and export. Learn named and default exports, module scope, live bindings, dynamic import() and import maps.

Small scripts fit in one file. Real applications don't. Once a project has a few thousand lines, you need a way to split code into files, give each file a clear job, and decide exactly what each file shares with the others. That's what modules do.

A JavaScript module is simply a file that uses export to share some of its values and import to use values from other files. Everything else in the file stays private. Modules have been part of the language since ES2015, work natively in every modern browser and in Node.js, and are the format that build tools, packages and frameworks are built around. This lesson covers the syntax, the rules that make modules different from classic scripts, and loading code on demand with import().

About the examples. A module normally lives in its own file, but the editors on this page can't create files. Multi-file examples are therefore shown as read-only code, with a comment naming each file. The live demos build small modules on the fly from data: URLs and Blob URLs, which the browser loads exactly like files.

Exporting and importing

Here is a tiny project with two files. math.js exports two functions and a constant; app.js imports what it needs:

JavaScript
// math.js
export const PI = 3.14159;

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

export function round(value, decimals = 2) {
  const factor = 10 ** decimals;
  return Math.round(value * factor) / factor;
}

const secretHelper = () => "not exported"; // private to this file
JavaScript
// app.js
import { circleArea, round } from "./math.js";

console.log(round(circleArea(3))); // 28.27

These are named exports: each exported value has a name, and the importing file asks for those names inside curly braces. The names must match. Asking for something the module doesn't export is an error when the module loads, before any code runs, which catches typos early.

You can also write the exports in one list at the bottom of a file, which some people find easier to scan:

JavaScript
// math.js
const PI = 3.14159;
function circleArea(radius) { return PI * radius ** 2; }

export { PI, circleArea };

Renaming and importing everything

Use as to rename on either side, which helps when two modules export the same name:

JavaScript
import { round as roundNumber } from "./math.js";
import { round as roundDate } from "./dates.js";

export { circleArea as area }; // export under a different name

To grab every export at once, import a namespace object:

JavaScript
import * as math from "./math.js";

math.circleArea(2);
math.PI;

Default exports

A module can also have one default export, its "main" value. It's imported without curly braces, under any name you choose:

JavaScript
// Toast.js
export default class Toast {
  constructor(message) { this.message = message; }
  show() { console.log("๐Ÿ””", this.message); }
}

export const DURATION = 3000; // named exports can live alongside
JavaScript
// app.js
import Toast, { DURATION } from "./Toast.js";
import Popup from "./Toast.js"; // same class, different local name

new Toast("Saved!").show();

Named or default? Many teams prefer named exports for almost everything. They keep the same name across the codebase, editors can auto-import them reliably, and a misspelled name fails loudly. Default exports are common for "one thing per file" modules such as components. Both are fine; be consistent within a project.

Now try it live. The browser can import a module from a data: URL, so the first line below imports from a module whose whole source code is inside the URL. It has a default export and a named export:

JS A static import from a data: URL

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In a real project, the part after from would be a path such as "./greet.js".

How the browser loads modules

In a web page, a module script uses type="module":

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

The browser fetches app.js, finds its import statements, fetches those files, and so on until it has the whole module graph. Then it runs the modules, dependencies first. A few details:

  • Module scripts are deferred automatically. They run after the HTML has been parsed, like <script defer>, so you rarely need DOMContentLoaded. The Adding JavaScript lesson covers script loading in the page.
  • Paths must be explicit. In the browser, write "./math.js", "../lib/math.js" or a full URL, including the .js extension. Bare names such as "lodash" fail unless an import map (below) or a build tool resolves them.
  • Each module runs only once. If ten files import math.js, it is fetched and executed a single time, and all ten get the same exports. That makes modules a natural place for shared state, like a settings object.
  • Modules are fetched with CORS and need a server; opening an HTML file straight from your disk (file://) usually blocks them. A local development server solves that.

What makes a module different from a script

Modules follow slightly different rules than classic scripts:

  • Module scope. Top-level variables are private to the module. They don't become globals or properties of window, so two modules can both have a const count without clashing.
  • Strict mode is always on. No "use strict" needed; the stricter rules from Strict Mode apply automatically.
  • Top-level this is undefined, not window.
  • Top-level await is allowed, as you saw in async and await. A module that awaits delays the modules that import it until it finishes.
  • import.meta holds information about the current module; import.meta.url is its own URL, handy for finding files next to it.
JS Module rules in action

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Imports are live, read-only bindings

An import is not a copy. It's a live view of the variable inside the exporting module. If the module changes the variable, every importer sees the new value. But importers can't assign to it themselves; only the owning module can.

The demo below creates two modules from Blob URLs. counter exports a variable and a function that changes it; the main code imports both and watches the value update:

JS Live bindings

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last line confirms that importing the same URL twice gives you the same module instance: modules run once and are shared.

Dynamic import()

Static import statements must sit at the top level of a module, and they all load before the module runs. Sometimes you want to load code later, or only when needed: a heavy chart library when the user opens the Reports tab, a translation file for the chosen language, an admin tool only for admins.

import(specifier) does this. It's a function-like expression that works anywhere (even in classic scripts), and it returns a promise for the module's namespace object:

JavaScript
const button = document.querySelector("#show-chart");

button.addEventListener("click", async () => {
  const { drawChart } = await import("./charts.js"); // downloaded on first click
  drawChart(document.querySelector("#chart"), salesData);
});

Build tools treat each import() as a split point and put that code in a separate file, a technique called code splitting. Your first page load gets smaller, and the extra code arrives only if it's used.

JS Loading a module on demand

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Note that import() hands you the namespace object, so a default export is found under .default.

Import maps

Packages from npm are usually imported by bare name: import { format } from "date-fns". Browsers don't know where "date-fns" lives, so traditionally a bundler rewrote those imports. An import map lets the browser do it directly. It's a JSON block that maps names to URLs, placed before any module script:

HTML
<script type="importmap">
  {
    "imports": {
      "date-fns": "/vendor/date-fns/index.js",
      "utils/": "/js/utils/"
    }
  }
</script>

<script type="module">
  import { format } from "date-fns";       // โ†’ /vendor/date-fns/index.js
  import { slugify } from "utils/text.js"; // โ†’ /js/utils/text.js
</script>

A key ending in / maps a whole folder. Import maps are supported in all current browsers. They're great for small sites and prototypes without a build step. Larger projects usually rely on the tools from the next lesson instead.

CommonJS: the older format you'll still meet

Before standard modules existed, Node.js created its own system, CommonJS, which you'll see in older packages and tutorials:

JavaScript
// CommonJS (Node.js): not the standard syntax
const fs = require("fs");
module.exports = { readConfig };

This is also how you reach a variable that lives in another file. A top-level variable in one module is private to it, so the file that owns it must export it and the other file must import it. With CommonJS in Node.js the two files look like this (read-only; the standard-module version is at the top of this lesson):

JavaScript
// module1.js
const appName = "Shop";
module.exports = { appName };

// module2.js
const { appName } = require("./module1.js");
console.log(appName); // Shop

Run it with node module2.js. In the browser, a plain <script> file shares its top-level var and function names through the global object, which is exactly the clutter modules were designed to remove.

Modern Node.js supports standard modules too: use the .mjs extension or set "type": "module" in package.json. For new code, prefer import and export everywhere.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. utils.js has export function slugify() {}. Which import is correct?

    Named exports are imported by name inside curly braces. Without braces you would be asking for the default export.
  2. 2. How many default exports can one module have?

    A module may have zero or one default export, plus any number of named exports.
  3. 3. A module declares const total = 0; at its top level. Is total a global variable?

    Modules have their own scope. Other files can only see what the module exports, and only after importing it.
  4. 4. What does await import("./charts.js") give you?

    Dynamic import resolves to the namespace object. Named exports are properties; the default export is on .default.
  5. 5. Why does import { format } from "date-fns" fail in a plain browser page with no tooling?

    Browsers only understand URLs and relative paths. An import map can map the bare name to a URL.

Summary

  • A module is a file that shares values with export and uses others' values with import; everything else stays private.
  • Named exports are imported in braces by name; a module can have one default export, imported without braces.
  • Load modules in the browser with <script type="module">; use explicit paths with extensions.
  • Modules run once, in strict mode, with their own scope, top-level await and this set to undefined.
  • Imports are live, read-only bindings to the exporting module's variables.
  • import() loads modules on demand and returns a promise; import maps let browsers resolve bare package names.

Next: Packages, npm and Build Tools โ€” what npm, bundlers, transpilers and linters do for you.