JavaScript Modules
A module is a JavaScript file with its own scope. Names inside a module stay inside it unless the module exports them.
Load a module and read its export
The Blob holds one line of module code. The dynamic import loads it, and the greeting is read from the loaded module.
(async () => {
const url = URL.createObjectURL(new Blob(["export const greeting = 'Hello from a module';"], { type: "text/javascript" }));
const module = await import(url);
console.log(module.greeting);
})();Names stay inside the module
secret is not exported, so it never leaves the module. shown is exported, so the main script can read it.
(async () => {
const url = URL.createObjectURL(new Blob(["const secret = 'hidden'; export const shown = 'visible';"], { type: "text/javascript" }));
const module = await import(url);
console.log(module.shown);
console.log(typeof secret);
})();A module loads only once
Two imports of the same address return the same module. The check with === gives true, and the value is 7.
(async () => {
const url = URL.createObjectURL(new Blob(["export const value = 7;"], { type: "text/javascript" }));
const first = await import(url);
const second = await import(url);
console.log(first === second);
console.log(first.value);
})();Example
(async () => {
const url = URL.createObjectURL(new Blob(["export const add = (a, b) => a + b; export const multiply = (a, b) => a * b;"], { type: "text/javascript" }));
const math = await import(url);
console.log(math.add(3, 4));
console.log(math.multiply(3, 4));
})();Key points
- Module: a JavaScript file with its own scope
- Export: a name a module shares with other files
- Import: a request that loads a module and reads its exports
- A name that is not exported stays private to its module.
- Blob: a piece of data held in memory, like a file without a name
- Blob URL: a short address that points at a Blob, so the browser can load it
- A dynamic import loads a module when the code asks for it, not at the start.
In this example, a small math module exports two named functions. The main script loads the module with a dynamic import. It then calls add and multiply through the loaded module.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What is a module in JavaScript?