ES Modules: import, export, and type=module
Lesson 18 of 38 in the JavaScript learning path.
How do I split browser JavaScript into modules?
An ES module is a file with its own scope. export marks the bindings other files may use, and import reads those names from a URL. In the browser the entry file is a script whose type is module. That script is deferred, so it runs after the document is parsed, and it is strict, so an accidental assignment cannot create a global. Module URLs resolve from the importing file and stay on the same origin unless the server sends CORS headers.
The sample splits a course player into js/format.js and js/main.js. The format module exports a track name and a list renderer that uses textContent. The main module imports those names and paints the list. The preview inlines the same functions so one document can run, while the sample shows the real import.
Syntax & Parameters
export function formatMinutes(total) {}
import { formatMinutes } from "./format.js";
<script type="module" src="/js/main.js"></script>
Example
Interactive preview available// js/format.js
export const TRACK = 'JavaScript';
export function formatMinutes(total) {
const minutes = Math.max(0, Math.round(Number(total) || 0));
return `${minutes} min`;
}
export function formatPercent(value) {
const percent = Number(value);
if (!Number.isFinite(percent)) return '0%';
const clamped = Math.min(100, Math.max(0, Math.round(percent)));
return `${clamped}%`;
}
export function formatLessonCard(lesson) {
const title = String(lesson?.title ?? 'Untitled');
return `${title} (${formatMinutes(lesson?.minutes)})`;
}
export function renderLessonList(root, lessons) {
root.replaceChildren();
for (const lesson of lessons) {
const item = document.createElement('li');
item.textContent = formatLessonCard(lesson);
root.append(item);
}
}
// js/main.js
import { TRACK, formatLessonCard, formatPercent, renderLessonList } from './format.js';
const lessons = [
{ title: 'Scope', minutes: 8, percent: 40 },
{ title: 'Modules', minutes: 9, percent: 15 },
];
const lines = lessons.map((lesson) => {
return `${formatLessonCard(lesson)} · ${formatPercent(lesson.percent)}`;
});
const root = document.querySelector('#module-output');
if (root !== null) {
const heading = document.createElement('p');
heading.textContent = TRACK;
const list = document.createElement('ul');
renderLessonList(list, lessons);
root.replaceChildren(heading, list);
}
console.log(TRACK);
console.log(lines.join('\n'));
Expected Output
Console: JavaScript Scope (8 min) · 40% Modules (9 min) · 15% #module-output shows the heading JavaScript and a list: Scope (8 min) Modules (9 min)
Line-by-Line Walkthrough
- The first banner is js/format.js. export const TRACK shares one string without creating a global binding.
- formatMinutes rounds a number, refuses a negative result, and returns a label such as 8 min.
- formatPercent clamps a finite number into 0 through 100 and adds a percent sign. A non-number becomes 0%.
- formatLessonCard reads title and minutes with optional chaining and falls back to Untitled when the title is missing.
- renderLessonList clears the root and appends an li for each lesson, using textContent so titles stay text.
- The second banner is js/main.js. The import line names TRACK, formatLessonCard, formatPercent, and renderLessonList from ./format.js.
- That relative URL is resolved from js/main.js, so the browser requests js/format.js on the same origin.
- lessons is local to the module. map builds the console lines, including the clamped percent, without mutating the source objects.
- When #module-output exists, the module creates a paragraph and a list, renders the lessons into the list, and replaces the root children.
- The console prints the track and the two lines. A script with type=module is deferred and strict, so this file runs after the markup and cannot leak a global by accident.
Common Pitfalls & Security
Modules do not run from a file URL in a normal browser page, and a classic script tag will not treat import as an import. The type must be module, and the src must be an HTTP URL on the same origin unless the other origin sends CORS headers. Import names are live bindings, but a typo is a load error, not a null. Forgetting the file extension in the browser URL fails the fetch. A module is strict, so a sloppy assignment that used to create a global now throws.
- <script src="/js/main.js"> without type=module treats import as a syntax error.
- import names that are not exported fail the module graph. The page stays blank and the error is in the console.
- Cross-origin module scripts need CORS. Same-origin files under /js do not.
- Putting secrets in a module still ships them to the browser. A module is not a private server file.
- root.innerHTML = title parses markup. A title equal to the untrusted string <img src="x" alt="untrusted"> is an XSS hole. Keep using textContent inside the renderer.
Best Practices & Modern Standards
Put shared formatters in a small module and keep the page entry in main.js. Export functions and constants by name so the importer is explicit. Load the entry with type=module and a same-origin src. ES2024 modules are deferred and strict by default, which replaces the older pattern of a defer attribute plus a strict-mode directive on every file.
Pass the DOM node into the render function so the module can be read without reaching for a hard-coded id, and still look that id up once in the entry file. Keep student strings in textContent. When the graph grows, add files rather than a bundle step until the course site actually needs one. The browser can load the native modules directly.
Real-World Use
A course player used to keep formatting, storage, and the lesson list in one long script. Splitting format.js out lets the progress dashboard and the player share formatMinutes and formatPercent without copying them. main.js imports those helpers, renders the current lessons, and stays the only file the HTML points at.
The script tag uses type=module, so it waits for the document and runs in strict mode without a second attribute. The preview on a single document page inlines the same functions because a second file is not available there. The production player keeps the real import and serves both files from the same origin.
Frequently Asked Questions
Does type=module imply defer?
Yes. A module script downloads without blocking the parser and runs after the document is parsed, in order with other module scripts. You do not add the defer attribute. It also runs in strict mode.
Why does the import URL include .js?
Browser imports use URL resolution, not a bundler lookup. ./format.js is a real path next to main.js. Leaving off the extension requests a URL the server usually does not provide, and the module fails to load.
Can a module see variables from a classic script?
Only if that classic script created an explicit global, such as a property on window. Module scope is private. Prefer import and export over globals so each file declares what it uses.
Why does the preview inline the functions?
A single HTML document cannot load ./format.js when that file is not deployed beside it. The preview repeats the exported functions and comments the import line. The code sample is the version that uses the real import.