After this lesson you can split a program into several small files that share only what you choose. You will use export and import, load modules from an HTML page, and load code on demand.
Why modules
A small project fits in one file. A larger one does not, and the old fix, several <script> tags, had a flaw: every top-level variable became global, so files could overwrite each other's names, and you had to get the tag order exactly right. A module is a file with its own private scope. Nothing leaks out unless you export it, and any file that wants something must import it by name. The dependencies are written in the code, rather than hidden in the order of script tags.
Named exports
Put export in front of a declaration to share it. Here is a file called math.js:
// math.js
export const TAX_RATE = 0.18;
export function add(a, b) {
return a + b;
}
export function withTax(price) {
return Math.round(price * (1 + TAX_RATE) * 100) / 100;
}
let hidden = 0; // not exported, so private to this fileAnother file picks what it needs, by the same names, inside braces:
// main.js
import { add, withTax, TAX_RATE } from "./math.js";
console.log(add(2, 3)); // 5
console.log(withTax(100)); // 118
console.log(TAX_RATE); // 0.18The path starts with ./ for "this folder" and includes the .js extension. In browsers, the extension is required, because the path is a real web address. Any name not exported, like hidden, cannot be reached from outside.
You can rename on the way in with as: import { withTax as priced } from "./math.js". And you can import everything as one object: import * as math from "./math.js", then use math.add(1, 2). That object lists exports in alphabetical order when you inspect it, with Object.keys(math) giving [ 'TAX_RATE', 'add', 'bump', 'counter', 'inc', 'withTax' ] for a file that also exported bump, counter and inc.
Default exports
A module may also have one default export, often used when the file is about a single thing.
// greet.js
export default function greet(name) {
return `Hello, ${name}!`;
}
// main.js
import greet from "./greet.js"; // no braces; any name would do
console.log(greet("Asha")); // Hello, Asha!Because the importer chooses the name, defaults can become inconsistent between files. Many teams prefer named exports for that reason. Either style works; just keep to one in a project. A default and named exports can be mixed: import greet, { add } from ....
Live bindings and read-only imports
Imports are not copies. They are live, read-only views of the exporter's variable. If math.js exports let counter = 0 and an inc() function that does counter++, then after calling inc() the importing file sees counter become 1 (it prints 0, then 1). But the importer cannot assign to it: math.TAX_RATE = 1 throws TypeError: Cannot assign to property 'TAX_RATE' of [object Module]. Only the module that owns a value can change it.
Using modules in a web page
Add type="module" to the script tag:
<script type="module" src="main.js"></script>Modules behave a little differently from classic scripts:
- They run in strict mode automatically.
- Each has its own scope.
letandfunctionat the top level do not become globals. Inside a module,thisat the top level isundefined. - They are deferred: they run after the page has been parsed, like
defer, so the elements they select exist. - Each module file runs once, even if ten files import it. All importers share the same instance.
- You can use
awaitat the top level, with no async wrapper.
Here is a runnable module script. The inline form works the same, only the code is in the page rather than in its own file.
<pre id="out"></pre>
<script type="module">
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const answer = await Promise.resolve(42);
log("top-level await:", answer);
log("this at top level:", String(this));
log("typeof window.answer:", typeof window.answer);
</script>top-level await: 42
this at top level: undefined
typeof window.answer: undefinedThe third line shows that answer stayed private to the module and did not become a property of window. Try changing type="module" to nothing in the editor: the top-level await becomes a syntax error and nothing runs.
Loading on demand with import()
The import { ... } from form must sit at the top of the file and is always loaded first. When you want to load code only when it is needed, for example a big chart library after a click, use the function form import(), which returns a promise:
const lazy = await import("./greet.js");
console.log(typeof lazy.default); // function
console.log(lazy.default("Ravi")); // Hello, Ravi!The default export is on the default property of the result, and named exports sit beside it. This pairs well with async and await and keeps your first page load small.
Modules in Node
Node supports the same syntax. A file is treated as a module when it ends in .mjs or when the nearest package.json has "type": "module". Older Node code uses require() and module.exports; that is a different system called CommonJS, which you will still see in many older tutorials.
Running modules locally
If you double-click an HTML file that uses type="module" with separate files, the browser reads it from a file:// address and usually blocks the imports, printing a CORS error in the console. The fix is to serve the folder over http. For example, with Node installed you can run npx serve in the folder, or use your editor's live-preview feature, and open the http://localhost address it prints. The error is about origins, not about your code.
Common mistakes
- Leaving out the extension.
import { add } from "./math"fails in a browser. Write"./math.js". - Leaving out
./.import ... from "math.js"is treated as a package name, not a file next to you. - Mixing up braces.
import add fromexpects a default export, andimport { add } fromexpects a named one. A wrong choice gives "does not provide an export named" orundefined. - Forgetting
type="module". You get "Cannot use import statement outside a module". - Opening the page from disk. Serve it over http.
- Expecting globals. A function defined in a module is not visible to an inline
onclick="..."attribute. Attach listeners in JavaScript instead. - Circular imports. Two files importing each other can leave one reading a value before it is set. Move shared code into a third file.
- Reassigning an imported name. Imports are read-only; ask the owner to export a function that changes it.
Exercise
Make three files in a folder: math.js exporting add and multiply, format.js with a default export money(n) that returns "Rs. " + n.toFixed(2), and main.js that imports both and logs money(add(2, 3)). Create index.html loading main.js with type="module", and open it through a local server. Then try opening the file straight from disk and read the console error.
Next, take a look at some newer syntax that makes everyday code shorter: Optional chaining and other modern syntax.
Key points
- A module is a file with its own scope, so nothing is shared unless you export it and another file imports it.
- Named exports are imported by name inside braces, and a file can have one default export that you import under any name.
- In a browser, load a module with script type="module" and a relative path that includes the .js extension.
- Imports are live read-only views of the exporting file, and modules run once, in strict mode.
- import() loads a module on demand and returns a promise, and modules must be served over http, not opened from file://.