AdvancedLesson 24 of 306 min read

Modules: import, export and organising code

Split programs into modules with import and export, use them in the browser, and structure a project in clear files.

In this lesson you will

  • Export and import named and default values
  • Use modules in the browser
  • Structure a project into files with single jobs
  • Load code on demand with import()

About 20 minutes

One big file is a bad idea

Imagine a recipe book with every recipe written on one endless scroll, in no particular order. Finding anything would be painful, and a mistake in one place could ruin another. Large programs face the same problem. The solution is to split code into small files, each with one clear job, and let them share what they choose. In JavaScript these files are called modules.

Exporting from a module

// math.js
export const PI = 3.14159;

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

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

const secret = 42;           // not exported: private to this file

Importing into another file

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

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

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

// import everything under one name
import * as math from "./math.js";
console.log(math.PI);

Anything not exported stays private. That is a big gain: your files can have their own variables without clashing with the others, and no accidental globals.

Default exports

// Logger.js
export default class Logger {
  log(msg) { console.log("[LOG]", msg); }
}

// app.js
import Logger from "./Logger.js";   // no braces; any name works
const logger = new Logger();

A file can have one default export and any number of named exports. Named exports need braces when importing and must match the name. Many teams prefer named exports because the names stay consistent across the project and editors can auto-complete them.

Using modules in the browser

<script type="module" src="app.js"></script>
  • Module scripts are deferred automatically, so no defer needed.
  • They run in strict mode.
  • Each file has its own scope: top-level variables are not global.
  • Each module runs only once, even if imported in many places.
  • File paths must start with ./, ../ or / and include the extension.
  • They must be served over http(s), not opened from file://. Use a local server such as the VS Code Live Server extension, or npx serve.
Good to know

The editors in these lessons run a single snippet, so they cannot load separate files. The practice below shows the same ideas inside one script using an object that stands in for a module. Try the real thing on your own computer with three small files.

This stand-in ‘module’ keeps secret data private with a closure and exports only two functions. Add a third exported function, reset, that sets the count back to zero.

const counterModule = (function () {
  let count = 0;            // private
  function increment() { count++; return count; }
  function current() { return count; }
  return { increment, current };   // the exports
})();

counterModule.increment();
counterModule.increment();
console.log(counterModule.current());
console.log(counterModule.count);   // undefined: private

Add function reset() { count = 0; } and include it in the returned object.

const counterModule = (function () {
  let count = 0;            // private
  function increment() { count++; return count; }
  function current() { return count; }
  function reset() { count = 0; }
  return { increment, current, reset };   // the exports
})();

counterModule.increment();
counterModule.increment();
console.log(counterModule.current());
counterModule.reset();
console.log(counterModule.current());
console.log(counterModule.count);   // undefined: private

A tiny project in three files

// storage.js : only knows how to save and load
export function load(key, fallback = []) {
  try { return JSON.parse(localStorage.getItem(key)) ?? fallback; }
  catch { return fallback; }
}
export function save(key, value) {
  localStorage.setItem(key, JSON.stringify(value));
}
// todos.js : the rules of the app, no DOM here
import { load, save } from "./storage.js";

let todos = load("todos");

export const getTodos = () => [...todos];
export function addTodo(text) {
  todos.push({ id: Date.now(), text, done: false });
  save("todos", todos);
}
// app.js : connects the page to the logic
import { getTodos, addTodo } from "./todos.js";

document.querySelector("#form").addEventListener("submit", (e) => {
  e.preventDefault();
  addTodo(e.target.elements.text.value);
  render(getTodos());
});

Each file has one responsibility: storage knows nothing about the page, the todo rules know nothing about HTML, and the app file glues them together. You can change how data is saved by editing one file. This separation is the heart of maintainable programs.

Dynamic imports

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

import() is a function that returns a promise. It lets you load heavy code, such as a charting library, only when the visitor asks for it, which keeps first page loads fast.

Modules, npm and bundlers

  • npm is the world’s biggest library of shared JavaScript packages. npm install downloads them into node_modules.
  • Packages use import too: import confetti from "canvas-confetti".
  • Bundlers such as Vite and esbuild combine and optimise your modules for production. Beginners can start with Vite: npm create vite@latest.
Common mistake

Opening an HTML file with module scripts by double-clicking it. Browsers block module loading from file:// for security, and you see a CORS error in the console. Serve the folder through a local server instead.

Another common mistake

Mixing up named and default imports: import add from "./math.js" when add is a named export gives undefined. Named exports need braces: import { add } ....

One job per file

If you struggle to name a file, it probably does too many things. Names like storage.js, validators.js and render.js are good signs that your structure is healthy.

Try it: module scope in action

A classic script puts its top-level variables on the page’s global object, where any other script can read or overwrite them. A module keeps its own. The inline module below shows the difference. Read the output, then change the module script so it also creates a classic-style global with window.shared = 'visible' to see how a module has to share something deliberately.

Run the page and read the two lines. Then add window.shared = ‘visible’ inside the module and see the output change.

<pre id="out" style="font-family:monospace;font-size:14px"></pre>
<script>
  var classicVar = 'I am global';
</script>
<script type="module">
  const moduleConst = 'I am private to this module';
  const out = document.getElementById('out');
  out.textContent =
    'classic var on window: ' + window.classicVar + '\n' +
    'module const on window: ' + window.moduleConst + '\n' +
    'shared on window: ' + window.shared;
</script>

Add window.shared = ‘visible’; at the top of the module script, before out.textContent.

<pre id="out" style="font-family:monospace;font-size:14px"></pre>
<script>
  var classicVar = 'I am global';
</script>
<script type="module">
  window.shared = 'visible';
  const moduleConst = 'I am private to this module';
  const out = document.getElementById('out');
  out.textContent =
    'classic var on window: ' + window.classicVar + '\n' +
    'module const on window: ' + window.moduleConst + '\n' +
    'shared on window: ' + window.shared;
</script>

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does the export keyword do?

  1. Deletes it
  2. Makes it global
  3. Makes something available to other files
  4. Saves it to disk

Only exported items can be imported.

How do you enable modules in the browser?

  1. <script modern>
  2. <module>
  3. <import>
  4. <script type="module">

type=”module” turns on module behaviour.

How many default exports can a file have?

  1. Two
  2. One
  3. Unlimited
  4. None

A file has at most one default export.

Why do module scripts fail when opened from file://?

  1. Modules are slow
  2. JavaScript is off
  3. Browsers block module loading for security
  4. They need npm

Serve the folder through a local server.

What does await import("./chart.js") do?

  1. Loads the module only when that code runs
  2. Imports at the start always
  3. Deletes chart.js
  4. Exports chart.js

Dynamic imports load on demand.

Summary

  • export shares, import uses.
  • Use script type=”module” and serve over http.
  • Each file should do one job.
  • import() loads code only when needed.

Next lesson

Next: error handling and debugging, keeping programs calm when things go wrong.

Questions

Named or default exports?

Named exports keep names consistent and help editors. Default exports suit a file with one main thing. Pick a style and keep it.

Do I need npm to use modules?

No. Modules work natively in browsers. npm is for installing other people's packages.

What is CommonJS?

The older module system used by Node (require and module.exports). Modern Node also supports import and export.

Progress is saved in this browser.