Modules

Topic 1 of 2 in Modules & packages6 min readBeginnerFree course

Overview

As programs grow, one file becomes hard to manage. Modules let you split code into files, each with its own scope, and share only what you choose.

Without modules, every script on a page shares one global scope: two files that both declare const total clash, and nothing tells you which file depends on which. With modules:

  • each file is private by default — its variables are invisible to other files;
  • a file exports the things it wants to share;
  • other files import exactly what they need, and the dependencies are written at the top for anyone to see.

math.js keeps const secret private and exports PI and area; Course.js has a default export, class Course. app.js imports area and PI from ‘./math.js’ by name and Course from ‘./Course.js’ as the default. A dashed box shows await import(‘./editor.js’), loaded only when needed.

Named exports

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

export function area(r) {
  return PI * r * r;
}
JavaScript
// app.js
import { area, PI } from './math.js';
import { area as circleArea } from './math.js'; // rename on import
import * as math from './math.js';               // everything as one object
math.area(2);

You can also export a list at the bottom of a file, which gives a neat summary of what the module offers:

JavaScript
function area(r) { … }
function circumference(r) { … }

export { area, circumference };

Default exports

A module can have one default export, imported without braces under any name:

JavaScript
// Course.js
export default class Course {}

// app.js
import Course from './Course.js';

A file can have a default export and named exports: import Course, { validate } from './Course.js';.

Prefer named exports. They keep names consistent across files and work better with editor auto-imports.

Import paths

  • Relative paths start with ./ or ../ and include the file extension in the browser: './utils.js', '../lib/api.js'.
  • Bare names like 'date-fns' refer to installed packages. Browsers don’t understand these on their own — a build tool (Vite, Astro, webpack) or an import map resolves them. See the next topic.
  • Full URLs work too: import confetti from 'https://cdn.jsdelivr.net/npm/canvas-confetti/+esm';.

Using modules in the browser

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

Module scripts are deferred automatically, always run in strict mode, and need to be served from a web server (not opened as a file:// page). VS Code’s Live Server extension, or npx serve in a terminal, gives you one in seconds.

You only add the entry file to the HTML. The browser reads its import lines, fetches those files, reads their imports, and so on, building the whole graph.

How modules behave

  • A module runs once. If ten files import utils.js, it’s evaluated once and all ten get the same exports. That makes modules a natural place for shared state, like a single settings object.
  • Imports are live and read-only. You can’t reassign an imported variable (PI = 3 throws), but if the exporting module changes it, importers see the new value.
  • Top-level await works in modules: const config = await (await fetch('/config.json')).json();.
  • this at the top level is undefined, not window.

Loading on demand

import() loads a module only when you need it:

JavaScript
button.addEventListener('click', async () => {
  const { openEditor } = await import('./editor.js');
  openEditor();
});

Static import statements must sit at the top level of a file and are loaded before the code runs. import() is a function that can appear anywhere — inside an if, a click handler — and returns a promise. It keeps the first page load fast by leaving big, rarely used features out until someone asks for them.

Organising a project

A common layout groups code by job:

Text
src/
├── main.js          entry point: wires everything together
├── api.js           fetch helpers
├── state.js         shared data
├── ui/
│   ├── cart.js
│   └── toast.js
└── utils/
    └── format.js

Keep each module focused on one thing, and avoid two modules importing each other (a circular dependency) — it works in some cases but causes confusing undefined values in others.

CommonJS: the older style

In older Node.js code you’ll see a different module system:

JavaScript
const fs = require('fs');        // import
module.exports = { slugify };    // export

That’s CommonJS. Modern Node.js supports the standard import/export (called ES modules) too, and new code should prefer them.

Exercise

Export and import

Export a slugify function from utils.js, then import and use it in main.js. Bonus — also export a constant SEPARATOR = '-' and use it inside slugify.

JavaScript
// utils.js
function slugify(text) {
  return text.toLowerCase().replaceAll(' ', '-');
}

// main.js
console.log(slugify('Hello World'));

Summary

  • Each module file has its own scope; share things with export.
  • Named exports are imported in braces; a default export is not.
  • In the browser, load the entry file with <script type="module">; it follows the imports.
  • Module code runs once, in strict mode, and is deferred automatically.
  • import() loads a module on demand and returns a promise.