Sub topic 1
What Makes a File a Module
An ES module is a JavaScript file that the runtime loads under module rules instead of classic script rules. The two kinds of file use nearly the same syntax. The way they behave is different in three areas: scope, strictness, and structure. This chapter explains those differences so that the rules in later chapters have a clear basis.
Prerequisites
This chapter assumes you already know:
- Core JavaScript syntax: variables, functions, objects, and destructuring.
- The difference between
let,const, andvar, including howvarat the top level of a classic script creates a property on the global object. - Promises and
async/await. - How to run a file in a browser or with Node.js (
node file.js).
You don't need any prior experience with import or export.
The Host Decides, Not the File
A file does not declare itself a module. The host environment (the browser or Node.js) decides how to parse it, based on how the file is loaded:
- Browser: a file loaded with
<script type="module">, or imported by another module, is a module. A plain<script>is a classic script. - Node.js: a
.mjsfile is a module. A.jsfile is a module when the nearestpackage.jsoncontains"type": "module". A.cjsfile is always CommonJS.
The chapters on running modules in the browser and in Node.js cover the details. For now, the point is that the same source text can mean different things depending on the loader.
Module Scope
In a classic browser script, top-level var declarations and function declarations become properties of the global object, and every script shares one global namespace. In a module, top-level declarations stay in module scope. That scope is private to the file. Code in other files can reach a value only if the module exports it and the other file imports it.
Save this as scope-demo.mjs and run node scope-demo.mjs:
// scope-demo.mjs
var greeting = 'hello';
function helper() {
return 'helped';
}
console.log(typeof globalThis.greeting); // 'undefined'
console.log(typeof globalThis.helper); // 'undefined'
console.log(greeting, helper()); // 'hello helped'
console.log(this); // undefinedThe globals still exist. A module can read globalThis, console, or window, and it can assign to them explicitly. The difference is that its own declarations don't leak out.
The last line shows a second difference. At the top level of a module, this is undefined. In a classic browser script it is the global object, and in a CommonJS file it is module.exports.
| Behavior | Classic browser script | CommonJS (Node.js) | ES module |
|---|---|---|---|
| Top-level `var` becomes a global property | Yes | No | No |
| Top-level `this` | `window` (global object) | `module.exports` | `undefined` |
| Strict mode | Only with `'use strict'` | Only with `'use strict'` | Always |
| `import`/`export` declarations allowed | No (SyntaxError) | No (SyntaxError) | Yes |
| Top-level `await` | No | No | Yes |
| Evaluated how many times | Once per script tag | Once per resolved path (cached) | Once per resolved URL |
Strict Mode Is Always On
Module code always runs in strict mode. You can't turn it off, and adding 'use strict' changes nothing. Code written for sloppy mode may therefore fail in two different ways, and they need different fixes.
Some violations are runtime errors. The file loads and then throws when the offending line runs:
// strict-runtime.mjs
try {
undeclaredTotal = 42; // assigning to an undeclared name
} catch (err) {
console.log(err.name, err.message);
// ReferenceError undeclaredTotal is not defined
}
function whoAmI() {
return this;
}
console.log(whoAmI()); // undefined, not the global object
const frozen = Object.freeze({ x: 1 });
try {
frozen.x = 2;
} catch (err) {
console.log(err.name); // TypeError
}Other violations are early errors. The parser rejects them, so the whole module fails to load and no line of it runs, including lines before the problem:
withstatements.- Legacy octal literals such as
010(write0o10instead). delete someVariableon a plain identifier.- Duplicate parameter names, as in
function f(a, a) {}. - Using
argumentsorevalas a variable name.
Modules add a few rules of their own on top of strict mode. await is a reserved word everywhere in a module, which is what makes top-level await possible. HTML-like comments (<!--) are not allowed.
Static Structure
The biggest difference is that a module's imports and exports are static. The engine can find all of them by parsing the file, without running any code. Three rules follow from that.
importandexportdeclarations may only appear at the top level of the module. They can't be placed inside a function, anifblock, or atryblock.- The module specifier (the string after
from) must be a string literal. A variable or template literal with substitutions is not allowed. - Import declarations are hoisted. All imported modules are loaded and linked before any code in the importing module runs.
These lines are all SyntaxErrors in a module:
if (useFast) {
import { area } from './math.js'; // SyntaxError: not at top level
}
const path = './math.js';
import { area } from path; // SyntaxError: specifier must be a string literalThe third rule produces behavior that looks odd at first. Create these two files in the same folder:
// math.js
export function area(radius) {
return 3.14159 * radius * radius;
}// main.mjs
console.log(area(2)); // 12.56636, even though the import is below
import { area } from './math.js';For main.mjs to load math.js as a module, Node.js must treat .js as a module. Add a package.json containing { "type": "module" } to the folder, or rename the file to math.mjs and update the import. Then run node main.mjs. The call works because the engine resolved the import while it was linking modules, before main.mjs started executing. Even so, put imports at the top of the file, where readers expect them.
When you really need a conditional or computed load, use dynamic import(). It is an expression that returns a promise, and a later chapter covers it.
Why the Restrictions Are Worth It
Static structure lets tools and engines know the full dependency graph before any code runs:
- The runtime can fetch all dependencies in parallel and report a missing file or a misspelled export name before execution starts.
- Bundlers can drop exports that nothing imports (tree shaking).
- Editors can offer accurate autocompletion and rename refactoring across files.
Module scope removes accidental global collisions, and strict mode removes a set of silent failures. These guarantees explain the rules in the rest of this tutorial: live bindings, the linking and evaluation phases, and how circular dependencies behave.
Exercise
A classic browser script contains var count = 0; at the top level, and another classic script on the same page reads window.count. Both files are switched to <script type="module"> with no other changes. What does the second file now read, and why?
Show answer
It reads undefined. In a module, the top-level var count lives in module scope and does not become a property of the global object. To share the value, the first file should export it and the second should import it. Assigning to window.count explicitly would also work, but that brings back the global coupling that modules are meant to remove.
Exercise
A module begins with console.log('start'); and later contains the line const mode = 010;. When the module loads, is 'start' printed? Explain.
Show answer
No. The legacy octal literal 010 is an early error under strict mode, which modules always use. The parser rejects the whole file before any code runs, so console.log('start') never runs, and neither does any module that depends on this one.
Exercise
Why does import { area } from './math.js'; work when it appears below the line that calls area, while import { area } from someVariable; is a SyntaxError?
Show answer
Import declarations are static and hoisted. The engine finds them while parsing and links the imported bindings before the module runs, so their position in the file doesn't affect availability. That process requires the specifier to be known at parse time, so it must be a string literal. A variable's value only exists at runtime. For specifiers computed at runtime, use dynamic import().