Sub topic 6
Running Modules in the Browser
This chapter assumes you know the export and import forms from earlier chapters, and that relative specifiers like ./math.js need a full path with a file extension. It also assumes you can open a page in a browser and read its developer console.
Marking a Script as a Module
A browser treats a script as a classic script unless you tell it otherwise. Add type="module" to turn on import and export:
<!-- index.html -->
<!DOCTYPE html>
<html>
<body>
<script type="module" src="./main.js"></script>
</body>
</html>// main.js
import { area } from './math.js';
console.log(area(3));// math.js
export const PI = 3.14159;
export function area(radius) {
return PI * radius * radius;
}Module scripts behave differently from classic scripts in four ways:
| Behavior | Classic script | Module script |
|---|---|---|
| Strict mode | Opt-in | Always on |
| Top-level variables | Become globals | Stay private to the module |
| Execution timing | Blocks parsing unless `defer`/`async` | Deferred by default |
| Same URL included twice | Runs twice | Runs once |
Serve Files over HTTP
Browsers fetch modules with CORS rules, so opening index.html from a file:// URL fails. Run a local server from the project folder instead:
python3 -m http.server 8000Then visit http://localhost:8000. The server must also send JavaScript files with a JavaScript MIME type such as text/javascript. Most development servers do this already.
Bare Specifiers and Import Maps
A browser cannot resolve a bare specifier such as 'lodash-es/debounce.js' on its own, because it has no node_modules lookup. An import map tells it which URL each bare name stands for:
<script type="importmap">
{
"imports": {
"lodash-es/": "/vendor/lodash-es/"
}
}
</script>
<script type="module">
import debounce from 'lodash-es/debounce.js';
import { area } from './math.js';
console.log(area(3));
</script>A key ending in / maps a whole prefix, so lodash-es/debounce.js resolves to /vendor/lodash-es/debounce.js. Put the import map before any module script that depends on it.
Common Errors
| Console message (wording varies) | Cause | Fix |
|---|---|---|
| `Cannot use import statement outside a module` | Missing `type="module"` | Add the attribute |
| Blocked by CORS policy, origin `null` | Page opened from `file://` | Use a local HTTP server |
| `Failed to resolve module specifier "lodash-es"` | Bare specifier with no import map entry | Add an import map entry or use a relative path |
| 404 for `./math` | Extension left off | Write `./math.js` |
| Disallowed MIME type | Server sends wrong `Content-Type` | Configure the server |
Exercise
A page has <script type="module" src="./app.js"></script> written twice, and app.js contains console.log('loaded'). How many times does "loaded" print, and why?
Show answer
Once. The browser keys module instances by resolved URL. The second script tag reuses the module that is already loaded and does not evaluate it again.
Exercise
main.js contains import { format } from 'date-fns'; and the console says the specifier failed to resolve. The library's ES module files are served at /libs/date-fns/index.js. What do you add to the page?
Show answer
An import map placed before the module script: <script type="importmap">{ "imports": { "date-fns": "/libs/date-fns/index.js" } }</script>.