ECMAScript modules
suggest changeEach ECMAScript module has a private top-level scope. Export only the functions, classes, or values that other modules need.
// greetings.js
export function greet(name) {
return `Hello, ${name}!`;
}
export function repeat(message, count = 2) {
return Array.from({ length: count }, () => message);
}
export class Greeter {
greet(name) {
return greet(name);
}
}
Import named exports with braces:
import { greet, Greeter } from './greetings.js';
console.log(greet('Bob'));
const greeter = new Greeter();
console.log(greeter.greet('Alice'));
Import the entire module namespace when several exports need a shared qualifier:
import * as greetings from './greetings.js';
console.log(greetings.greet('Alice'));
Aliases resolve naming conflicts without changing the exporting module:
import { greet as formatGreeting } from './greetings.js';
These imports are static and must appear at the module's top level. Use dynamic import() for conditional loading.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents