Chapter 13: Module Systems and Bundlers
Chapter 13 of 15
Chapter 13: Module Systems and Bundlers
13.1 ES6 Modules
ES6 modules provide a standardized way to organize and share code. They use static imports/exports and support tree-shaking.
// Exporting (math.js)
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
export function multiply(a, b) {
return a * b;
}
// Default export
export default function subtract(a, b) {
return a - b;
}
// Importing (app.js)
import subtract, { PI, add, multiply } from './math.js';
// or
import * as math from './math.js';
console.log(math.add(2, 3));
Dynamic Imports:
// Load module on demand
async function loadModule() {
const module = await import('./heavy-module.js');
module.doSomething();
}
// Conditional loading
if (condition) {
const { feature } = await import('./feature.js');
feature();
}
13.2 CommonJS (Node.js)
// Exporting
module.exports = {
add: (a, b) => a + b,
subtract: (a, b) => a - b
};
// or
exports.multiply = (a, b) => a * b;
// Importing
const { add, subtract } = require('./math');
const math = require('./math');
13.3 Module Bundlers
Webpack: Most popular, highly configurable
Vite: Fast, uses native ES modules
Parcel: Zero-configuration bundler
Rollup: Optimized for libraries
13.4 Tree Shaking
Tree shaking eliminates unused code from the final bundle.
// Only used functions are included in bundle
import { add } from './math.js';
// multiply and subtract are not included if unused