JavaScript Modules in Browsers and Node: script type=module, Import Maps, Dynamic import(), Top-level await and CommonJS Interop
Using ES modules for real: script type=module and its loading behavior, CORS and local servers, import maps, modulepreload, dynamic import() for lazy loading, top-level await, import.meta, JSON imports, Node's ESM vs CommonJS rules, require(esm), and bundlers.
kvi5hnuCode Sprout team member9 min readOn this page
Articles 74 and 75 covered module syntax. This one covers how modules actually run: in browsers, in Node, and through build tools. It also covers the dynamic features: loading code on demand with import(), waiting at the top level with await, and finding files relative to a module with import.meta.
Modules in the browser
script type="module"
A page opts in to module semantics with type="module":
<script type="module" src="./js/main.js"></script>
<script type="module">
import { startApp } from "./js/app.js";
startApp(document.querySelector("#root"));
</script>
The browser fetches main.js, reads its import declarations, fetches those modules, and so on until it has the whole graph. Only the entry point needs a <script> tag.
Module scripts differ from classic scripts in several ways:
- They're deferred automatically. Fetching happens in parallel with HTML parsing, and execution waits until the document is parsed, then follows document order, exactly like
<script defer>. So a module can safely query the DOM without waiting forDOMContentLoaded. asyncruns a module as soon as it and its imports have loaded, possibly before parsing finishes and out of document order. Use it for independent code like analytics.- They run once. The same module URL included twice runs only once.
- They're fetched with CORS. Modules from another origin need an
Access-Control-Allow-Originheader. - They need a real web server. Opening
index.htmldirectly from disk (file://) blocks module loading in most browsers. Use a local development server such asnpx serve, Vite, or your editor's live server. - Strict mode, module scope, and
this === undefinedat the top level (article 75). Top-level variables don't become globals. Assign towindow.something(orglobalThis.something) deliberately if a value really must be global.

You may still see <script nomodule src="legacy-bundle.js">, which only old browsers without module support run. Every browser in current use supports modules, so new projects don't need it.
Import maps: bare specifiers in the browser
In Node, import { format } from "date-fns" finds the package in node_modules. A browser has no node_modules, so a bare name like "date-fns" means nothing to it. An import map tells the browser what bare specifiers mean:
<script type="importmap">
{
"imports": {
"date-fns": "https://cdn.jsdelivr.net/npm/date-fns@4.1.0/+esm",
"utils/": "/js/utils/"
}
}
</script>
<script type="module">
import { format } from "date-fns"; // mapped to the CDN URL
import { debounce } from "utils/timing.js"; // mapped to /js/utils/timing.js
</script>
Import maps are supported in all major browsers. The map must appear before any module that uses it. They make small projects possible without a bundler, and they let you swap a library's version in one place.
Preloading
Because the browser discovers imports only after downloading each file, a deep import graph costs several round trips. <link rel="modulepreload" href="/js/app.js"> tells the browser to fetch (and parse) a module early. Bundlers generate these tags automatically.
Dynamic import()
Static import declarations load everything up front. import(specifier) loads a module on demand and returns a promise of its namespace object:
// file: main.js
const button = document.querySelector("#export");
button.addEventListener("click", async () => {
const { exportToPdf } = await import("./pdf-export.js"); // loaded on first click
exportToPdf(document.body);
});
Key facts:
- The specifier can be any expression, so it can be computed:
await import(`./locales/${lang}.js`). - It works in classic scripts and CommonJS too, not only in modules. In Node it's how CommonJS code loads an ES module that uses top-level await.
- The promise resolves to the same namespace object as
import * as ns; a default export is at.default:const { default: Chart } = await import("./chart.js");. - Modules are still cached: importing the same module again resolves to the same namespace without re-running it.
- If loading fails (network error, syntax error, missing file), the promise rejects, so handle errors with
try/catchand show a fallback. import()looks like a function call but is special syntax: you can't doconst load = import;.
Code splitting builds on this: bundlers turn each import() into a separate file (a "chunk") loaded only when needed. Routes in single-page apps, heavy editors, charts and admin panels are typical candidates. React's lazy(() => import("./Page.js")) and similar framework helpers are thin wrappers around it.
Top-level await
Inside a module (ES2022), await can be used at the top level, outside any async function:
// file: config.js
const response = await fetch("/config.json");
export const config = await response.json();
// file: main.js
import { config } from "./config.js"; // waits until config.js has finished
console.log(config.apiUrl);
Any module that imports config.js waits for its promise to settle before running, so importers always see initialized values. Other branches of the graph that don't depend on it can still load in parallel.
Use it for genuinely necessary setup (configuration, a database connection, a WebAssembly module), but sparingly: a slow top-level await delays every module that depends on it. Top-level await doesn't work in classic scripts or CommonJS files.
import.meta
import.meta is an object with information about the current module:
import.meta.url: the module's full URL (https://site/js/app.js, orfile:///home/ana/app/main.jsin Node).import.meta.resolve(specifier): resolves a specifier relative to the module and returns the URL, without loading it.- In Node,
import.meta.dirnameandimport.meta.filenamereplace CommonJS's__dirnameand__filename.
The usual job is locating files that sit next to the module, whatever page or working directory it's used from:
// file: i18n/index.js
export async function loadMessages(locale) {
const url = new URL(`./messages/${locale}.json`, import.meta.url);
const response = await fetch(url);
return response.json();
}
Importing JSON
Import attributes (ES2025) tell the host what kind of module to expect. JSON modules are the standard use:
import settings from "./settings.json" with { type: "json" };
console.log(settings.pageSize);
const { default: messages } = await import("./en.json", { with: { type: "json" } });
The with { type: "json" } part is required; without it, Node fails with ERR_IMPORT_ATTRIBUTE_MISSING and browsers refuse to load the file. This is a security measure: a server can't trick a page into running JavaScript when the page asked for data. JSON modules export the parsed data as their default export only.
ES modules in Node
Node supports both systems, so it needs to know which one each file uses:
| File | Treated as |
|---|---|
.mjs | always an ES module |
.cjs | always CommonJS |
.js in a folder whose nearest package.json has "type": "module" | ES module |
.js with "type": "commonjs" | CommonJS |
.js with no "type" | CommonJS, unless the file contains ES module syntax (import / export), in which case current Node versions detect it and run it as a module |
Setting "type": "module" explicitly is best for new projects: it's clear and avoids detection overhead. Inside ES modules in Node, file extensions are required in relative imports (./utils.js, not ./utils), and built-ins are best imported with the node: prefix: import { readFile } from "node:fs/promises";.
ESM and CommonJS interop
Importing CommonJS from an ES module works. module.exports becomes the default export, and Node also detects simple named exports by scanning the source:
// file: legacy.cjs
exports.add = (a, b) => a + b;
module.exports.version = 1;
// file: main.mjs
import legacy, { add } from "./legacy.cjs";
console.log(add(2, 3), legacy.version); // 5 1
Named detection only finds patterns like exports.name = ... and object literals of plain names. If a named import fails with Named export 'x' not found ... is a CommonJS module, import the default and destructure: import pkg from "./legacy.cjs"; const { x } = pkg;.
Loading an ES module from CommonJS used to require await import(). Current Node versions (20.19+, 22.12+, and all later releases) also let require() load ES modules synchronously and return the namespace object. The one exception: if the module graph uses top-level await, require throws ERR_REQUIRE_ASYNC_MODULE, and you must use import().
For the rare case where an ES module needs require (say, for a CommonJS-only tool's API), Node provides createRequire(import.meta.url) from node:module.
Bundlers and build tools
Even with native modules everywhere, most production web apps still go through a bundler (Vite, which uses Rollup and esbuild, or webpack, Rspack, Parcel):
- Fewer, smaller requests. Hundreds of small modules become a few optimized files, with modulepreload hints and code-split chunks for
import(). - Tree shaking. Because ES imports and exports are static, the bundler can see that you used only
debouncefrom a large utility library and drop the rest. This works best with named exports and modules without side effects. ("sideEffects": falsein a package'spackage.jsonpromises that unused files can be dropped.) - Transforms. TypeScript, JSX, CSS imports, minification and syntax lowering for older browsers.
- Bare specifiers and
node_modules. The bundler resolves npm packages the way Node does.
For learning, small tools and many internal pages, native modules plus an import map are enough. Part 17 covers the tool chain in more detail.
Common questions
Why does my module page show a CORS error when I open the HTML file directly?
Browsers load module scripts with CORS rules, and file:// pages have no proper origin, so module requests are blocked. Serve the folder over HTTP with any local development server.
How do I use __dirname in an ES module?
In Node, use import.meta.dirname (and import.meta.filename). In general, new URL(".", import.meta.url) gives the module's folder as a URL.
Should a new Node project use CommonJS or ES modules?
ES modules, with "type": "module" in package.json. They're the language standard, work in browsers and Node, support top-level await, and tooling increasingly expects them. Thanks to interop, CommonJS dependencies still work.
When should I use dynamic import?
For code that isn't needed immediately: rarely used features, large libraries used on one screen, per-language data, or modules chosen at runtime. For everything needed at startup, static imports load faster and let tools analyze your code.
Summary
<script type="module">loads a module graph; modules are deferred by default, run once, use CORS, need a web server, and are strict with their own scope.- Import maps give browsers bare specifiers;
modulepreloadfetches modules early. import(specifier)loads a module on demand, returns a promise of its namespace, works in scripts and CommonJS too, and powers code splitting.- Top-level
awaitlets modules finish async setup before importers run; use it sparingly. import.meta.url(plusdirnameandfilenamein Node) locates files relative to the module; JSON imports needwith { type: "json" }.- Node picks a module system per file by extension and
"type"; ESM can import CommonJS (as a default plus detected names), andrequire()can load ES modules without top-level await. - Bundlers combine modules, tree-shake unused exports, split code at
import()calls, and transform syntax.
Review quiz
Check your understanding of IIFE modules, CommonJS, ES module syntax, live bindings and modules in browsers and Node: Part 10 review quiz: Modules.
Practice Questions
A page has this module script followed by a classic <script src="b.js"></script>. Which runs first?
<script type="module" src="a.js"></script>
Answer
b.js. The classic script runs as soon as it's parsed and fetched, blocking the parser, while the module is deferred until parsing finishes.
Write code that loads ./charts.js only when a "Show chart" button is clicked and calls its default export with the chart container.
Answer
showButton.addEventListener("click", async () => {
const { default: renderChart } = await import("./charts.js");
renderChart(container);
});
This import fails in Node. Why, and what's the fix?
import data from "./data.json";
Answer
JSON modules require an import attribute declaring their type: the code below.
import data from "./data.json" with { type: "json" };
A CommonJS file calls require("./setup.mjs"), and setup.mjs contains await connect(); at the top level. What happens, and what should it do instead?
Answer
It throws ERR_REQUIRE_ASYNC_MODULE, because require is synchronous and can't wait for top-level await. Use const setup = await import("./setup.mjs"); inside an async function, or import("./setup.mjs").then(...).
Previous: ES Modules in JavaScript: import, export, Default vs Named Exports, Re-exports and Live Bindings
Next: JavaScript Set and Map: Unique Values, Key-Value Collections, Set Methods and When to Use Them

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.