ES Modules: import and export
8 min read
ES Modules
Modules let you split code into separate files and explicitly declare what each file exports and imports. Every .js file in a module context is in its own scope — nothing leaks to global.
Named Exports and Imports
javascript
// math.js
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export function multiply(a, b) { return a * b; }
// main.js
import { PI, add } from "./math.js";
console.log(add(2, 3)); // 5
// Rename on import
import { multiply as mul } from "./math.js";
// Import everything under a namespace
import * as math from "./math.js";
math.add(1, 2);Default Exports
javascript
// logger.js
export default function log(msg) {
console.log("[LOG]", msg);
}
// main.js
import log from "./logger.js"; // any name works
import myLog from "./logger.js"; // also validRe-exporting
javascript
// index.js — barrel file
export { add, multiply } from "./math.js";
export { default as log } from "./logger.js";ES modules are static — imports are resolved at parse time, not runtime. This enables tree-shaking (unused exports removed from the bundle). For dynamic loading, use import() which returns a Promise.
Ready to test yourself?
Practice JavaScript— quiz & coding exercises