JavaScript Reference ยท Statements and Declarations
The import declaration
Reference for the JavaScript import declaration: named, default and namespace imports, side-effect imports, live bindings, hoisting and where import is allowed.
The static import declaration brings bindings exported by another module into the current module. Imports are resolved and loaded before the importing module runs, so a missing file or a missing export is reported up front.
Imported names are live, read-only bindings: they always reflect the current value in the exporting module, and you cannot assign to them from the importer.
import { circleArea } from "./math.js"; import Logger from "./logger.js"; import * as utils from "./utils.js";
Try it
Live examples cannot load files, so this demo builds a module from a data: URL and imports it dynamically. The static forms are listed under Syntax.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
import defaultExport from "module"; import * as name from "module"; import { export1, export2 as alias } from "module"; import defaultExport, { export1 } from "module"; import defaultExport, * as name from "module"; import "module"; // side effects only import json from "./data.json" with { type: "json" };
| Part | Description |
|---|---|
defaultExport |
A local name for the module's default export. |
* as name |
A frozen-like namespace object with all named exports. |
{ ... } |
Named imports; as renames them. |
"module" |
The specifier: a relative path, an absolute URL, or a bare name resolved by an import map or bundler. |
with { ... } |
Import attributes, for example type: "json". Support is newer; check a compatibility table. |
Usage notes
- Top level only.
importdeclarations cannot appear inside functions or blocks. For conditional or lazy loading use dynamicimport(). - Hoisted. The imports are processed before any code in the module runs, wherever you write them.
- Runs once. A module is evaluated once, no matter how many places import it; all importers share the same instance.
- File extensions matter in browsers and Node.js: write
./math.js, not./math. - Browsers need
<script type="module">; in Node.js use.mjsor"type": "module"inpackage.json. - Circular imports work because bindings are live, but reading a binding before its module has run throws a
ReferenceError. - Naming. Prefer named imports for clarity; tree-shaking tools can drop unused ones.
Browser support
ES module imports work in all current browsers and Node.js. Import attributes (with) and JSON modules are newer; check a compatibility table.
Related
export, dynamicimport(),import.meta- ES modules
- Lesson: Modules