Sub topic 2
Running Modules in the Browser
This chapter assumes you already know the basic import and export syntax and are comfortable with promises and async/await. It covers how browsers and Node.js load modules, and then three behaviors that often surprise people: live bindings, re-exports, and dynamic loading.
Running Modules in the Browser
A <script type="module"> tag runs its code as a module. Module scripts are deferred by default and always run in strict mode. The browser fetches them with CORS, so opening the page from file:// fails. Serve the page over HTTP instead.
The browser does not understand bare specifiers such as lodash-es on its own. 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>Running Modules in Node.js
Node.js treats a file as an ES module when its name ends in .mjs, or when it is a .js file and the nearest package.json contains "type": "module". The exports field sets the package's public entry point:
{
"name": "geometry",
"version": "1.0.0",
"type": "module",
"exports": {
".": "./src/index.js"
}
}Imports Are Live Bindings, Not Copies
An imported name points at the exporting module's variable. It does not hold a copy of the value. When the exporter changes the variable, every importer sees the new value. Importers cannot assign to the binding themselves.
// counter.js
export let count = 0;
export function increment() {
count += 1;
}
// main.js
import { count, increment } from './counter.js';
console.log(count); // 0
increment();
console.log(count); // 1Re-exports and Barrel Modules
A barrel module collects the exports of several files into one entry point:
// shapes/index.js
export { area, perimeter } from './math.js';
export { default as log } from './logger.js';
export * from './polygons.js';
export * as units from './units.js';export * skips the default export, so you have to re-export a default by name, as the log line does.
Loading Code on Demand with import()
import() is an expression that returns a promise for the module's namespace object. Use it to load code only when the user needs it:
const button = document.querySelector('#show-chart');
button.addEventListener('click', async () => {
const { default: renderChart } = await import('./chart.js');
renderChart(document.querySelector('#chart'));
});Exercise
In main.js, you write import { count } from './counter.js'; and then count = 10;. What happens, and how should main.js change the count instead?
Show answer
The assignment throws a TypeError because imported bindings are read-only. To change the value, call a function exported by counter.js, such as increment(). The change then shows up through the live binding.