Sub topic 2
Where Modules Run: Browsers and Node.js
This chapter assumes you know import/export syntax, have used async/await, and have run JavaScript in a browser page or with Node.js. Before you use import() or top-level await, you need to know whether the runtime treats your file as an ES module. That decision controls which syntax is allowed and how the file is loaded.
Modules in the Browser
A browser treats a script as an ES module only when the <script> tag says so with type="module".
<!DOCTYPE html>
<html>
<body>
<div id="app"></div>
<script type="module" src="./main.js"></script>
</body>
</html>Module scripts behave differently from classic scripts:
- They run in strict mode automatically.
- Top-level variables belong to the module, not to
window. - They are deferred by default, so they run after the HTML is parsed.
- They are fetched with CORS. Opening the page through
file://usually fails, so serve it over HTTP. - Each module URL is evaluated once, however many times it is imported.
A classic script (no type, or type="text/javascript") cannot contain static import statements or top-level await. It can still call import(), because import() is an expression that returns a promise and works in classic scripts too.
Modules in Node.js
Node.js picks a module system for each file from its extension and the nearest package.json.
| File | Treated as |
|---|---|
| `.mjs` | ES module, always |
| `.cjs` | CommonJS, always |
| `.js` with nearest `package.json` `"type": "module"` | ES module |
| `.js` with `"type": "commonjs"` or no `type` field | CommonJS |
To make every .js file in a project an ES module, set the type field:
{
"name": "demo",
"version": "1.0.0",
"type": "module"
}Then this file runs as an ES module:
// main.js
import { readFile } from 'node:fs/promises';
const text = await readFile(new URL('./package.json', import.meta.url), 'utf8');
console.log(JSON.parse(text).name);node main.jsIf you remove "type": "module", Node.js loads main.js as CommonJS and the same code fails. Recent Node.js versions try to detect ES module syntax in ambiguous .js files, but relying on detection hides your intent. Set type or use .mjs explicitly.
What Each Context Allows
| Feature | ES module | Classic script / CommonJS |
|---|---|---|
| Static `import` / `export` | Yes | No |
| `import()` | Yes | Yes |
| Top-level `await` | Yes | No |
| `import.meta` | Yes | No |
| `require` (Node.js) | No, unless created with `createRequire` | Yes in CommonJS |
The import() row is why dynamic import works as a bridge between the two systems, which a later chapter covers. The top-level await row explains the most common error, SyntaxError: await is only valid in async functions and the top level bodies of modules. When you see that error, the file is almost always being loaded as CommonJS or as a classic script.
Exercise
A project has a package.json with no "type" field. The file tools/build.js contains top-level await and fails with a SyntaxError. Give two ways to fix it without wrapping the code in an async function.
Show answer
Rename the file to tools/build.mjs so Node.js always treats it as an ES module, or add "type": "module" to the nearest package.json so all .js files in that scope are ES modules. If you choose the second fix, check that any existing CommonJS .js files still work, or rename them to .cjs.
Exercise
A classic script (no type attribute) in a browser page calls import('./widget.js'). Does this work, and could the same script use a static import statement?
Show answer
Yes, the import() call works because dynamic import is allowed in classic scripts. A static import statement would be a SyntaxError, because static imports are allowed only in module scripts.