ES Modules (import / export)
ES Modules split code into reusable files. Use export to share functions/classes and import to use them. This is how all modern JavaScript projects are organized — React components, utility libraries, API layers.
ES Modules
- Named export — export function greet() { } or export { greet, utils }
- Default export — export default class User { }. One per file
- Named import — import { greet, utils } from './utils.js'
- Default import — import User from './User.js'. Can use any name
- Rename — import { greet as hello } from './utils.js'
- Import all — import * as utils from './utils.js'; access: utils.greet()
- script type='module' — <script type='module' src='app.js'>. Required in HTML
ES Modules Code
// ===== utils.js =====
// Named exports
export function add(a, b) {
return a + b;
}
export function multiply(a, b) {
return a * b;
}
export const PI = 3.14159;
// ===== User.js =====
// Default export (one per file)
export default class User {
constructor(name) {
this.name = name;
}
greet() {
return `Hello, ${this.name}!`;
}
}
// ===== app.js =====
// Named imports (must use same names)
// import { add, multiply, PI } from './utils.js';
// Default import (can use any name)
// import User from './User.js';
// import MyUser from './User.js'; // same thing, different name
// Import all
// import * as MathUtils from './utils.js';
// MathUtils.add(1, 2);
// Rename
// import { add as sum } from './utils.js';
// Re-export (barrel file: index.js)
// export { add, multiply } from './utils.js';
// export { default as User } from './User.js';
// Example usage
function add(a, b) { return a + b; }
function multiply(a, b) { return a * b; }
console.log("Modules: add(5,3) =", add(5, 3));
console.log("Modules: multiply(5,3) =", multiply(5, 3));Tip
Tip
Use named exports for utility functions (multiple items per file) and default exports for main component/class (one per file). This is the convention used by React, Vue, and most JavaScript libraries.
Use ESM for all new projects. CJS is legacy.
Common Mistake
Warning
Circular imports (A imports B, B imports A) cause undefined values and hard-to-debug errors. Structure your modules in a dependency tree — if you need shared utilities, extract them into a separate module that both can import.
Practice Task
Note
Module organization: (1) Create a utils.js with named exports for common functions. (2) Create a config.js with a default export. (3) Re-export from an index.js barrel file. (4) Practice tree-shaking by importing only what you need.
Quick Quiz
Key Takeaways
- ES Modules split code into reusable files.
- Named export — export function greet() { } or export { greet, utils }
- Default export — export default class User { }. One per file
- Named import — import { greet, utils } from './utils.js'