import and export
Module syntax for sharing code between files — any number of named exports, at most one default export per module.
export const x = 1; / export default fn; / import x, { y } from "./file.js";
Purpose
export makes a binding from one module (file) available to others; import brings it in. Each
module has its own scope — nothing is shared between files unless explicitly exported and imported.
Syntax
// math.js
export function add(a, b) {
return a + b;
}
export const PI_ROUNDED = 3.14;
export default function multiply(a, b) {
return a * b;
}
// app.js
import multiply, { add, PI_ROUNDED } from './math.js';
import { add as addNumbers } from './math.js'; // renaming on import
import * as math from './math.js'; // everything, as one namespace object
Behavior notes
- A module can have any number of named exports but at most one default export.
- Named exports must be imported by their exact exported name (or explicitly renamed with
as); a default export can be imported under any local name, since there’s only one. - Browsers load a module with
<script type="module" src="app.js">; module scripts defer automatically and always run in strict mode. - Node treats a file as a module either via a
.mjsextension, or a"type": "module"field inpackage.jsonapplying to.jsfiles in that package. - Import paths for local files must be relative (
./math.js) or absolute, including the file extension in most current tooling — unlike some older bundler configurations that allowed omitting it.
Common mistakes
- Forgetting the file extension in a relative import path where the runtime/tooling requires it.
- Mixing up named and default export syntax when importing —
import { multiply }for a default export throws, since default exports aren’t inside the named-export braces.
Runtime notes
ES modules are core ECMAScript, standard in every current browser and Node version. Older CommonJS
(require/module.exports) syntax still appears in many existing Node codebases — covered in the
Intermediate tier’s Node module.