JavaScript Modules & Tooling
ES Modules (ESM)
// math.js
export const add = (a, b) => a + b;
export default function multiply(a, b) { return a * b; }
// main.js
import multiply, { add } from './math.js';
import * as math from './math.js';
// Dynamic import (lazy loading)
const { add } = await import('./math.js');
CommonJS (Node.js)
// module.js
module.exports = { add: (a, b) => a + b };
// or
exports.add = (a, b) => a + b;
// main.js
const { add } = require('./module');
Key Differences: ESM vs CJS
| Feature |
ESM |
CJS |
| Loading |
Static, async |
Dynamic, sync |
| Tree shaking |
Yes |
Limited |
| Top-level await |
Yes |
No |
| Browser native |
Yes |
No |
| File extension |
.mjs or type:module |
.js / .cjs |
Modern Toolchain
- Bundlers: Webpack, Vite, Rollup, esbuild
- Transpilers: Babel (ES6+ → ES5), TypeScript
- Package manager: npm, yarn, pnpm
- Linters: ESLint
- Formatters: Prettier