Modules

suggest change

ECMAScript modules provide the standard import and export syntax. Modules have their own top-level scope, run in strict mode, and support top-level await.

Named exports

// math.js
export const pi = Math.PI;

export function circumference(radius) {
  return 2 * pi * radius;
}
// app.js
import { circumference, pi as circleRatio } from './math.js';

console.log(circumference(4), circleRatio);

Default and namespace imports

A module can have at most one default export:

// logger.js
export default function log(message) {
  console.log(message);
}
import log from './logger.js';
import * as math from './math.js';

log(math.circumference(4));

Static imports are resolved before the module executes. Use await import(specifier) when a module must be loaded conditionally or on demand.

In browsers, load an entry module with <script type="module" src="./app.js"></script>. Module scripts are deferred automatically and obey CORS rules. Current Node.js versions support ECMAScript modules through .mjs, the package.json "type": "module" setting, or other documented package rules.

Use explicit relative file paths in browser imports unless an import map or bundler defines bare specifiers. Imported bindings are live, read-only views of the exporting module's bindings.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents