Sub topic 2
Where Modules Run: Browsers and Node.js
The rest of this tutorial uses import() and top-level await, and both depend on how the runtime treats your file. A browser or Node.js decides up front whether a file is an ES module or a classic script. That decision controls which syntax is legal, how the file is loaded, and which global helpers exist. This chapter explains how each runtime makes that decision and the errors you get when it goes wrong.
This chapter assumes you can write import and export statements, that you have run JavaScript in a browser and in Node.js, and that you know what a package.json file is.
Two Kinds of JavaScript File
JavaScript code runs in one of two "goals" (the specification's word for parsing modes):
- A script is the classic format. It runs in sloppy mode unless it says
"use strict", and its top-levelvarand function declarations become globals. It cannot containimportorexportstatements. - A module always runs in strict mode and has its own top-level scope. It can use
import,export,import.meta, and top-level await.
The file's contents do not decide which goal applies. The runtime decides from outside the file: from an HTML attribute, a file extension, or a field in package.json. The import() expression is the one exception, because it is legal in both scripts and modules. That makes it the bridge between the two worlds, which later chapters cover.
| Feature | Classic script | ES module |
|---|---|---|
| `import` / `export` statements | Syntax error | Allowed |
| `import()` expression | Allowed | Allowed |
| Top-level await | Syntax error | Allowed |
| Strict mode | Opt-in | Always on |
| Top-level `this` | Global object (or `module.exports` in Node CommonJS) | `undefined` |
| Top-level `var` creates a global | Yes (browser) | No |
| `import.meta` | Syntax error | Allowed |
Modules in the Browser
Opting in with type="module"
A browser treats a <script> as a module only when it carries type="module":
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Module demo</title>
<script type="module" src="./main.js"></script>
<script nomodule src="./legacy-bundle.js"></script>
</head>
<body>
<p id="out">Loading...</p>
</body>
</html>// main.js
import { greeting } from './greeting.js';
document.querySelector('#out').textContent = greeting;
console.log(this); // undefined: module top-level this// greeting.js
export const greeting = 'Hello from an ES module';Browsers that support modules skip any script marked nomodule. Older browsers do not recognize type="module", so they ignore that script and run the nomodule fallback. All current browsers support modules, so nomodule matters only if you still ship to very old clients.
Loading behavior that differs from classic scripts
Module scripts follow different loading rules:
- Deferred by default. A module script does not block HTML parsing. It runs after the document is parsed, in document order with other deferred scripts. This applies to inline module scripts too, while classic inline scripts ignore
defer. asyncis honored. With<script type="module" async>, the module and its dependencies run as soon as they are ready, without waiting for parsing or for other scripts.- Evaluated once per URL. If two
<script type="module">tags, or twoimportstatements, point to the same resolved URL, the module is fetched and evaluated one time and shared. - Fetched with CORS. Cross-origin module scripts must be served with the correct
Access-Control-Allow-Originheader. Classic scripts have no such requirement. - Strict MIME check. The server must send a JavaScript MIME type such as
text/javascript. If it sendstext/plainorapplication/octet-stream, the browser refuses to run the module.
The file:// trap
Opening index.html by double-clicking it loads the page from a file:// URL. Chromium-based browsers then block the module fetch because a file:// page has an opaque (null) origin, so the CORS check fails. The console shows an error that mentions CORS policy and origin null.
The fix is to serve the folder over HTTP. Any static server works:
# Option 1: Python's built-in server
python3 -m http.server 8000
# Option 2: a Node-based static server from npm
npx http-server -p 8000Then open http://localhost:8000/.
Workers
Web workers default to classic scripts too. To use import inside a worker, pass { type: 'module' }:
const worker = new Worker(new URL('./worker.js', import.meta.url), {
type: 'module',
});
worker.postMessage('start');Modules in Node.js
Node.js supports two module systems. CommonJS (CJS) uses require() and module.exports. ES modules (ESM) use import and export. Node picks the system for each file by the rules below.
The decision rules
- A file ending in
.mjsis always ESM. - A file ending in
.cjsis always CommonJS. - For a
.jsfile, Node finds the nearestpackage.jsonby walking up from the file's folder. If that file has"type": "module", the.jsfile is ESM. If it has"type": "commonjs", or has notypefield, the file is CommonJS. - If there is no
typefield and the file contains ES module syntax, recent Node versions (22.7+ and 20.19+) detect this and run the file as ESM anyway. This is called syntax detection. Node may print a warning that suggests adding atypefield, because detection costs an extra parse.
Code passed through --eval or standard input follows the --input-type=module or --input-type=commonjs flag.
Set type explicitly. That avoids the detection cost and makes the file's meaning obvious to tools such as linters, test runners, and bundlers.
{
"name": "module-demo",
"version": "1.0.0",
"type": "module"
}With this package.json, every .js file in the package is ESM. If you need one CommonJS file, name it .cjs. The reverse also holds: in a CommonJS package, name an ESM file .mjs.
What changes inside a Node ES module
Several CommonJS globals are absent in ESM because they are injected by the CommonJS wrapper function, and ESM files have no wrapper:
| CommonJS | ES module replacement |
|---|---|
| `require('x')` | `import x from 'x'` or `import('x')` |
| `__filename` | `import.meta.filename` (Node 20.11+) or `fileURLToPath(import.meta.url)` |
| `__dirname` | `import.meta.dirname` (Node 20.11+) or `path.dirname(fileURLToPath(import.meta.url))` |
| `module.exports` | `export` statements |
| `require.resolve('x')` | `import.meta.resolve('x')` |
This script runs in any Node version that supports ESM:
// paths.mjs
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
const here = fileURLToPath(import.meta.url);
const dir = path.dirname(here);
console.log('This file:', here);
console.log('Its folder:', dir);
console.log('import.meta.url:', import.meta.url);
const pkgPath = path.join(dir, 'package.json');
try {
const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
console.log('Package type:', pkg.type ?? '(not set)');
} catch {
console.log('No package.json next to this file');
}Run it with node paths.mjs. Note that import.meta.url is a file:// URL, not a path. Pass it through fileURLToPath before giving it to APIs that expect a filesystem path. Otherwise the result breaks on Windows and on paths that contain spaces.
Resolution differences
Node's ESM loader is stricter than require():
- Relative imports need the full file extension.
import './utils'fails, andimport './utils.js'works. - Directory imports such as
import './lib'do not resolve to./lib/index.js. - Bare specifiers such as
'express'still resolve throughnode_modules, and the package'sexportsfield decides which file you get.
Common Errors and What They Mean
| Error message | Cause | Fix |
|---|---|---|
| `SyntaxError: Cannot use import statement outside a module` | An `import` statement is in a file the runtime treats as a script or CommonJS | Add `type="module"` to the script tag, rename to `.mjs`, or set `"type": "module"` |
| `ReferenceError: require is not defined in ES module scope` | `require` used in an ESM file | Use `import`, or rename the file to `.cjs` |
| `ReferenceError: __dirname is not defined in ES module scope` | CommonJS global used in ESM | Use `import.meta.dirname` or `fileURLToPath` |
| `ERR_MODULE_NOT_FOUND` for a file that exists | Missing `.js` extension in a relative import | Write the full filename |
| Browser: "blocked by CORS policy" with origin `null` | Page opened via `file://` | Serve over HTTP |
| Browser: "Expected a JavaScript module script but the server responded with a MIME type of ..." | Server sends the wrong Content-Type | Configure the server to send `text/javascript` |
Why This Matters for the Rest of the Tutorial
Top-level await works only in module contexts: type="module" scripts, .mjs files, or .js files in a "type": "module" package. The import() expression works everywhere, including classic scripts and CommonJS files. That is why import() is the standard way for CommonJS code to load an ES module, a topic covered in a later chapter. Before you debug either feature, confirm the context first. Many "dynamic import is broken" reports turn out to be a file running in the wrong mode.
Exercise
A project has a package.json with no "type" field. It contains build.js, which uses require(), and server.js, which uses import statements. The team wants to add "type": "module". Which file must be renamed, and to what?
Show answer
After adding "type": "module", every .js file is treated as an ES module, so build.js would fail with "require is not defined in ES module scope". Rename build.js to build.cjs so it stays CommonJS. server.js needs no change.
Exercise
You open index.html directly from your file manager. It contains <script type="module" src="./app.js">, and nothing runs. The console mentions CORS and origin 'null'. Why, and what is the fix?
Show answer
Module scripts are fetched in CORS mode. A page loaded from file:// has an opaque null origin, so the browser blocks the module request. Serve the folder over HTTP, for example with python3 -m http.server 8000, and open http://localhost:8000/.
Exercise
In a Node ES module, the line import { helper } from './helpers' throws ERRMODULENOT_FOUND even though helpers.js exists in the same folder. What is wrong?
Show answer
Node's ESM resolver does not add file extensions or search for index files. The import must name the file exactly: import { helper } from './helpers.js'.
Exercise
Which of these are legal in a classic browser script (no type="module"): an import statement, an import() call, top-level await, import.meta?
Show answer
Only the import() call. Import statements, top-level await, and import.meta are syntax errors outside module code.