ECMAScript modules are the standardized module system of JavaScript, defined by the ECMAScript language specification. They provide explicit syntax for exporting values from one module and importing them into another, together with rules for resolving dependencies, connecting bindings, and evaluating interconnected code. Introduced in ECMAScript 2015, the system supplies a common language-level foundation for modular JavaScript in browsers, server runtimes, and development tools.
The defining properties of ECMAScript modules include statically declared dependencies, module-local scope, and live bindings: an imported name refers to an exported binding rather than merely receiving a copy of its initial value. These properties support early error detection, predictable dependency analysis, and optimizations that would be difficult with unrestricted runtime loading. Dynamic import and top-level await extend this foundation to conditional loading and asynchronous initialization.
The language specification does not prescribe a universal way to find files, download resources, or interpret package names. Those responsibilities belong largely to the host environment. Consequently, understanding ECMAScript modules requires distinguishing their shared language semantics from the loading and resolution conventions of web browsers, Node.js, and build systems.
Origins and standardization
Early JavaScript programs commonly consisted of scripts loaded into a shared global environment. In a web browser, several script elements could introduce functions and variables used by later scripts, but their dependencies were implicit. Correct operation depended on loading order and on avoiding collisions between global names. Immediately invoked function expressions and namespace objects reduced some of these problems without providing a standardized dependency mechanism.
As JavaScript applications expanded, several incompatible module conventions emerged. CommonJS, widely associated with server-side JavaScript and Node.js, used functions such as require() and an export object exposed through module.exports. Its ordinary loading model was synchronous, which suited local files more naturally than network resources. Asynchronous Module Definition—usually abbreviated AMD—used a different interface designed for asynchronous loading, particularly in browsers. Libraries sometimes supplied wrapper code that recognized several environments and selected an appropriate export mechanism.
The standardization of modules was part of the broader ECMAScript 2015 revision developed through Ecma Technical Committee 39. That edition, published in 2015 and also known as ES6, introduced import and export declarations alongside features such as classes, lexical declarations, and arrow functions. The module design separated language semantics from host loading: ECMAScript specified how imports and exports behave, while browser and server specifications supplied resource discovery and retrieval rules. Native browser implementations arrived after the language specification, with support spreading across major browser engines during 2017 and 2018.
Later language editions expanded the system without replacing its core architecture. ECMAScript 2020 standardized dynamic import() and import.meta, allowing programs to request modules during execution and inspect host-provided module metadata. ECMAScript 2022 standardized top-level await, enabling a module’s initialization to depend on asynchronous work. These additions addressed limitations of exclusively static declarations while retaining the same underlying module graph and binding model.
The resulting standard is not simply a renamed version of CommonJS or AMD. Its imports are language constructs with linking semantics, rather than ordinary function calls or object-property assignments. At the same time, its adoption did not eliminate older systems. Existing packages, runtime compatibility requirements, and deployment practices produced a prolonged period of coexistence. Modern JavaScript projects can therefore contain standard ECMAScript modules alongside CommonJS dependencies, generated compatibility wrappers, and tool-specific transformations.
Declarations, exports, and module scope
A JavaScript source text can be parsed as a script or as a module. This distinction is a parsing and execution choice made by the host, not something universally determined by a filename extension. Static import declarations and export declarations belong to module syntax. A module need not contain either declaration: a browser script explicitly marked as a module, for example, remains a module even when it exports nothing.
Named exports associate externally visible names with local bindings. They can accompany declarations or appear in a separate export list:
// arithmetic.js
export const unit = 1;
function add(a, b) {
return a + b;
}
export { add, add as sum };
A consumer can import selected exports and rename them locally:
import { unit, add as combine } from "./arithmetic.js";
The braces in a named import specify a module import list; they are not an object-destructuring operation. An import without a binding, such as import "./initialize.js";, still establishes a dependency and causes the imported module to be evaluated for its effects.
A module can also expose one export under the special name default. The consumer chooses the local name used for that default import:
// formatter.js
export default function format(value) {
return String(value);
}
// consumer.js
import renderValue from "./formatter.js";
Default and named exports may coexist. A namespace import, written import * as arithmetic from "./arithmetic.js";, exposes the module’s exports through a namespace object. Re-export declarations support intermediary modules: export { add } from "./arithmetic.js"; forwards a selected export without creating a local binding named add. The declaration export * from "./arithmetic.js"; forwards named exports but excludes the default export. An explicit declaration can forward the default when required.
Module scope differs from the global scope of classic scripts. Top-level declarations remain inside the module and do not automatically become properties of the global object. Module code always uses strict-mode semantics, and top-level this is undefined. These rules reduce accidental global writes and remove several historical ambiguities of non-strict JavaScript, although they do not prevent a module from deliberately modifying globally accessible objects.
Static import and export declarations must appear at the module’s top level, rather than inside functions or conditionals. Their positions among other top-level statements do not make them ordinary sequential loading commands: dependencies are processed before the module body executes. Duplicate exported names and various conflicting declarations are syntax errors. Importing a nonexistent named export from a standard source-text module is instead generally detected when the graph is linked.
Live bindings and module namespace objects
The central semantic distinction between ECMAScript modules and many object-based module conventions is the live binding. An import refers to a binding maintained by the exporting module. If the exporter changes that binding, subsequent reads through the import observe the new value:
// counter.js
export let count = 0;
export function increment() {
count += 1;
}
// consumer.js
import { count, increment } from "./counter.js";
console.log(count); // 0
increment();
console.log(count); // 1
The importing module cannot assign to count. An attempted assignment throws a TypeError when executed. This restriction applies to the imported binding, not necessarily to the value it contains. If a module exports an object, another module may mutate that object’s properties unless the object is otherwise protected. Thus, an immutable import reference is not equivalent to deeply immutable exported data.
Default exports require a further distinction. export default expression; evaluates an expression and initializes the module’s default binding with the resulting value. It does not generally establish an ongoing connection to any variable mentioned in the expression. By contrast, export { value as default }; exports the existing local binding named value. If that binding is later reassigned, consumers of the default export observe the reassignment. This difference matters when a default export represents changing state rather than a fixed function or object.
A module namespace object provides a property-oriented view of exports. For a namespace import such as import * as counter from "./counter.js";, reading counter.count retrieves the current exported value. Namespace objects are special objects defined by ECMAScript, not ordinary mutable dictionaries. Their exported-name properties cannot be reassigned or deleted by consumers, they are non-extensible, and their prototype is null. Export names are exposed in a specified lexicographic order.
Some reflective details reveal why a namespace object cannot be understood simply as a frozen plain object. Export properties have descriptors reporting writable: true, but the object’s specialized internal assignment behavior rejects writes. The descriptor is compatible with the fact that an exported value may change through its original binding; it does not grant importers authority to change it. Consequently, Object.freeze() is not an appropriate general explanation of namespace behavior.
Copying a namespace object also loses part of its semantics. Object spread, destructuring into local variables, or assigning an imported property to another variable reads the value at that moment. The new property or variable does not automatically track later reassignment of the original export. This distinction between a live binding and a copied value is important for shared configuration, counters, runtime registries, and compatibility layers that convert modules into ordinary objects.
Dependency graphs, linking, and cyclic imports
Static imports describe a dependency graph whose nodes are modules and whose edges represent requested dependencies. Module processing is often explained in three broad stages: loading and parsing, linking, and evaluation. The exact specification algorithms and host interfaces are more detailed, but this division separates obtaining source code from connecting names and from executing module bodies.
During loading, the host resolves module specifiers and makes the required modules available. A module specifier is the string in a declaration such as import { value } from "./state.js";. The ECMAScript language does not universally define whether that string names a file, a network resource, or an entry in a package registry. Once the relevant module records are available, linking resolves imported names to exported bindings and constructs the environments required for execution. Missing or ambiguous exports can prevent successful linking before ordinary module-body side effects occur.
For an acyclic synchronous graph, dependencies are evaluated before modules that depend on them. A module imported through several paths is normally evaluated once for the same host-recognized module identity. This does not mean that identical source text is universally a singleton: different resolved identities, execution contexts, or host caches can produce distinct instances. A shared dependency is shared because the host and module machinery recognize the same module record, not because its source text happens to match.
Cycles are supported because bindings can be connected before every module body has run. Suppose module A imports a function from B, while B imports a value from A. The graph can still be linked, but successful evaluation depends on when B reads A’s value. Lexical bindings declared with let, const, or class cannot be read before initialization. An early read therefore causes a ReferenceError, rather than yielding a partially filled export object.
Function declarations illustrate the distinction between cyclic structure and unsafe timing. An exported function may be available through the initialization performed for module environments even before its module body executes. Nevertheless, calling that function can still fail if it immediately reads an uninitialized lexical binding. A cycle is therefore neither automatically erroneous nor automatically safe.
The specification handles cyclic graphs using strongly connected components and depth-first traversal mechanisms related to standard graph algorithms. Asynchronous evaluation adds further state, including pending dependencies and promises representing completion. In practical architectures, moving a read from module initialization into a function called later can change an invalid cyclic interaction into a valid one. Conversely, a seemingly minor top-level calculation may expose a previously dormant initialization-order problem.
Dynamic import and asynchronous initialization
Dynamic import() requests a module during execution and returns a Promise. Unlike a static import declaration, it can appear inside a function, conditional branch, or other expression context, and its specifier can be computed:
async function openEditor() {
const { createEditor } = await import("./editor.js");
return createEditor();
}
The fulfilled value is normally the requested module’s namespace object. Resolution, loading, linking, and evaluation must succeed before the import operation completes successfully. Failures are reported through rejection, allowing the caller to handle unavailable resources, invalid syntax, missing exports, or exceptions during initialization through ordinary promise mechanisms.
Dynamic import is available in contexts beyond module source text, including supported classic-script environments. Its use does not mean that the target is interpreted as a classic script: the requested resource is processed according to the host’s module rules. Repeated successful imports of the same recognized module generally reuse its existing instance. Therefore, dynamic import is a loading interface, not a general command to re-execute a file from the beginning.
Top-level await addresses a different problem: asynchronous work required before a module is ready for its consumers. A module can await a configuration request, initialize a database connection, or select a dynamically imported implementation before completing its body. In the following example, a dependent module cannot complete its own ordinary evaluation until the imported configuration module has completed:
// configuration.js
const response = await fetch("./configuration.json");
if (!response.ok) {
throw new Error("Configuration request failed");
}
export const configuration = await response.json();
Top-level await does not freeze the entire runtime or indiscriminately block every module in the graph. It suspends the evaluation of the relevant module and delays modules whose execution depends on its completion. Other eligible work can proceed through the host’s event loop and asynchronous scheduling mechanisms. This behavior connects module evaluation directly to asynchronous programming rather than treating initialization as necessarily synchronous.
The interaction with cycles requires particular care. An asynchronous module may depend, directly or indirectly, on work that cannot occur until that same module finishes. Some such arrangements remain unsettled or otherwise fail according to the operations involved; cycle support does not guarantee progress for arbitrary asynchronous dependencies. Rejected initialization also propagates to dependent evaluation and to dynamic import callers.
A specialized edge case concerns an exported callable named then. Because dynamic import fulfills a promise with a namespace object, promise resolution may treat that object as a thenable and invoke the exported then function. Static namespace imports do not perform this promise assimilation. This unusual interaction follows from the combination of module namespaces and the general promise-resolution protocol, rather than from a separate module-loading feature.
Browser loading, URLs, and import maps
In HTML, a script element with type="module" selects module processing:
<script type="module" src="/app/main.js"></script>
A normal parser-inserted module script does not have the same parser-blocking execution behavior as a classic script without defer or async. Its evaluation is deferred until document parsing has finished and its dependencies are ready. Adding async changes scheduling: the module graph can execute when ready rather than waiting for the usual deferred ordering. Top-level await can further separate the start of evaluation from its eventual completion.
Browser module specifiers are normally interpreted through URL resolution. Relative paths are resolved against the referring module’s URL, not against whichever HTML document happens to import it. Browsers do not ordinarily search directories or append .js automatically. A bare specifier such as "utility-library" has no built-in package-directory meaning and requires an applicable mapping or another supported host mechanism.
Import maps supply declarative mappings from specifiers to URLs. They are embedded in HTML using a script element with type="importmap" and a JSON body. An imports object defines general mappings, while scopes can select mappings according to the importing module’s URL. Prefix mappings can redirect an entire family of specifiers when both the key and target use the required trailing-slash form. Import maps affect resolution; they do not install packages, combine source files, or transform language syntax.
Browser module fetching is also subject to web-platform security and resource rules. Cross-origin module requests use CORS, so a publicly reachable resource may still be unavailable as a module unless the server supplies appropriate access-control headers. JavaScript module responses must have an acceptable JavaScript media type. A server returning an HTML error page for a missing module therefore produces a loading failure even if the response has a successful status code. Local file: URLs also do not behave like a conventional HTTP-hosted module application.
The host-defined import.meta object exposes metadata associated with the current module. In browsers, import.meta.url identifies the module’s URL, enabling expressions such as new URL("./image.png", import.meta.url). The underlying ECMAScript construct is standardized, but individual properties and additional methods depend on the host.
Module loading extends to supported worker environments, where a worker can be created with a module type. Browsers also offer modulepreload links to begin work on module resources before their ordinary discovery. These mechanisms alter resource acquisition and execution context without changing live bindings or export semantics. Import attributes can additionally indicate an expected module type, such as JSON, where the browser supports that module format.
Node.js, packages, and CommonJS interoperability
Node.js implements ECMAScript modules alongside its older CommonJS system. The two share JavaScript syntax and values but differ in loading, scope, resolution, and export representation. Explicit format indicators include .mjs for ECMAScript modules and .cjs for CommonJS. A package’s package.json can use "type": "module" or "type": "commonjs" to specify the interpretation of applicable .js files. Additional detection behavior has evolved across Node.js releases, so these explicit indicators remain important when describing reproducible package behavior.
Node’s ECMAScript module resolver recognizes relative and absolute references as well as package-oriented bare specifiers. Relative file imports ordinarily require their full filename, including the extension; Node does not apply all the extension-search and directory-index conventions familiar from CommonJS require(). Package metadata can define public entry points through "exports", including subpaths and conditional selections. The "imports" field supplies package-internal mappings, conventionally using names beginning with #.
Conditional exports can select different entry points for import and require consumers, or for other supported conditions. This permits compatibility with both module systems, but it can also create two independently initialized implementations of what appears to be the same package. If those implementations maintain state, consumers may encounter distinct registries, incompatible class identities, or duplicated singleton objects. Package boundaries and module identity therefore matter beyond surface syntax.
Importing CommonJS from ECMAScript modules is supported through an interoperability layer. The default import exposes the CommonJS module.exports value. Node also attempts to identify certain named exports by static analysis of common assignment patterns, but these inferred names do not have the full semantics of native ECMAScript live bindings. A CommonJS export constructed through arbitrary runtime computation cannot always be represented accurately as statically discoverable named exports.
The reverse direction has changed over Node’s history. Recent releases support require() for eligible synchronous ECMAScript module graphs under defined conditions, whereas older releases commonly required dynamic import. Graphs involving top-level await cannot be handled as ordinary synchronous require() operations. Dynamic import remains an important bridge from CommonJS code to modules whose loading or evaluation is asynchronous.
ECMAScript modules also lack the automatic CommonJS wrapper variables require, module, exports, __filename, and __dirname. Node supplies alternatives through its module APIs and import.meta, with the available properties depending on the runtime version. Built-in facilities can be identified explicitly with the node: scheme, as in import { readFile } from "node:fs/promises";. These conventions belong to Node’s host environment; they are not requirements imposed on browser modules or on all ECMAScript implementations.
Build tools, static analysis, and type systems
The static structure of import and export declarations makes ECMAScript modules particularly useful to compilers, development servers, and module bundlers. A tool can parse a module, identify its declared dependencies, and construct much of the program graph without executing the module’s ordinary statements. This is more tractable than discovering dependencies from unrestricted calls whose arguments and behavior may be determined only at runtime.
Bundlers use that graph to produce deployment artifacts. They may combine many modules into one file, partition them into several chunks, rewrite resource references, or preserve selected external imports. Dynamic import often serves as a split point: a feature and its dependencies can become a separate chunk loaded only when requested. The exact relationship between a source-level module and an output file is therefore a tool decision, not a property guaranteed by ECMAScript.
Tree shaking removes code that a build tool can establish is unnecessary. Explicit exports and imports make it possible to trace which bindings are used, but unused exports alone are not sufficient grounds for removing every associated statement. A top-level function call may register an event handler, modify shared state, or perform an externally observable operation. Safe elimination depends on side-effect analysis, package metadata, and assumptions encoded in the build configuration.
For example, a module exporting ten utility functions may permit the removal of nine unused function bodies. A module that also executes a registration function when imported may still need that initialization preserved. Package declarations such as a "sideEffects" field are build-tool conventions that help express such distinctions; they do not change the language’s evaluation rules. Incorrect metadata can cause a valid build transformation to remove behavior that the application expected.
TypeScript introduces another layer by distinguishing runtime values from types. An import type declaration is a TypeScript construct used for compile-time relationships and is erased from emitted JavaScript. Runtime imports must still conform to the target host’s module rules. TypeScript’s resolver and emission settings consequently need to model the intended environment, including Node package conditions or bundler-specific resolution. Acceptance by the type checker does not by itself prove that a browser or server can load the resulting specifier.
Transforming ECMAScript modules into CommonJS or another format also raises semantic constraints. A transformation may emulate live exports using getters, but handling cycles, namespace details, asynchronous initialization, and evaluation order can require more than replacing import with require(). Source maps help connect generated output to original modules during debugging, while tests executed only against transformed code may fail to expose differences that appear under native module loading.
Security boundaries, identity, and performance
Module scope is an organizational boundary, not a security sandbox. Imported code generally executes with the capabilities available in its environment. Browser code can interact with exposed web APIs, while a Node.js dependency may have access to files, processes, or network facilities according to the runtime’s permissions and configuration. Explicit imports reveal dependencies more clearly, but they do not make a dependency trustworthy or restrict its authority automatically.
On the web, security controls operate at several layers. CORS controls whether a browser may make a fetched resource available under the relevant cross-origin rules. Content Security Policy can restrict permitted script execution and loading. Subresource Integrity can bind certain fetched resources to expected cryptographic digests when supported by the relevant loading mechanism. Protecting an entry module does not automatically establish the integrity of every transitive dependency: the entire loading graph and the platform’s applicable controls remain significant.
Module identity has both correctness and resource implications. Hosts typically cache modules by resolved identity within an appropriate loading context. In URL-based systems, changing a query string can create a distinct module identity even when the server returns the same source text. Such modules may repeat initialization and maintain separate state. Conversely, importing the same recognized identity repeatedly does not provide an unloading or reset operation. ECMAScript exposes no universal API for clearing a host’s module cache.
Performance depends on graph shape, transfer behavior, parsing costs, and execution work rather than simply on the number of import declarations. Native modules can avoid a mandatory bundling step and enable browser-level reuse of resources, but dependency discovery can introduce network round trips. HTTP multiplexing reduces some connection-related overhead without removing request latency, server work, or the cost of compiling many small resources. Preloading, caching, and bundling address different parts of that problem.
Dynamic loading can reduce the initial download and evaluation burden, but it shifts latency to the moment a feature is first needed. Excessively coarse chunks may download substantial unused code; excessively fine partitioning may create many requests and scheduling overheads. Top-level asynchronous initialization adds another dimension, because a small module can delay a large dependent graph if its awaited operation is slow.
Error timing also follows the module architecture. Syntax and linkage errors can prevent a graph from starting, evaluation exceptions can interrupt initialization, and dynamic import converts loading and evaluation failure into promise rejection. Operational analysis therefore distinguishes a resource that was never fetched, a module that failed to link, and a module whose body began but did not complete successfully. These are different failure modes even when an application ultimately reports all of them as an unavailable feature.