**ES modules** provide a clean way to split code across files. Use **named exports** for multiple values, **default export** for the primary value. Modules are evaluated once and cached — the same module object is shared. In browsers, add `type="module"` to script tags. Node.js uses `.mjs` or `type: module` in package.json.
1Understanding Import & Export
ES modules provide a clean way to split code across files. Use named exports for multiple values, default export for the primary value. Modules are evaluated once and cached — the same module object is shared. In browsers, add type="module" to script tags. Node.js uses .mjs or type: module in package.json.
Modules are loaded asynchronously and run in strict mode automatically.
// utils.js
export const VERSION = '2.0.0';
export function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
export class Logger {
log(msg) { console.log(`[${new Date().toISOString()}] ${msg}`); }
}2Practical Example
Here is a real-world application of Import & Export showing how it is used in production JavaScript code.
// app.js
import { VERSION, capitalize, Logger } from './utils.js';
import { add as sum } from './math.js'; // rename on import
import * as utils from './utils.js'; // import all as namespace
const logger = new Logger();
logger.log(`App v${VERSION} starting...`);
console.log(capitalize('hello')); // Hello3Best Practices
Follow these guidelines when working with Import & Export:
1. Use named exports for libraries (treeshakeable)
2. Use default export for the main thing a module does
3. Keep one concern per module
Tip: Modules are loaded asynchronously and run in strict mode automatically.
// utils.js
export const VERSION = '2.0.0';
export function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
export class Logger {
log(msg) { console.log(`[${new Date().toISOString()}] ${msg}`); }
}