Lesson 14 / 25
Building for different targets
Configure Webpack for different environments.
Multi-target builds
Web applications need different builds for browsers, Node.js libraries, and web workers. Set target: 'web' for browser, 'node' for Node.js, 'webworker' for workers. Each target affects how Webpack handles globals and imports, producing appropriately compiled output.
Configure build targets
Set target based on deployment environment.
module.exports = (env) => ({
target: env.target || 'web',
// target options:
// 'web': browser (default)
// 'node': Node.js
// 'webworker': web worker
// 'electron-main': Electron main process
entry: './src/index.js',
output: { filename: 'bundle.js' }
});
Output:
npm run build -- --env target=node
Target affects built-ins
Browser target polyfills missing APIs. Node target exposes Node built-ins like fs, path. Web worker target disables code that needs DOM. Choose target to match your deployment context for correct module handling.
Quick check
Quick check: Which target should you use for a Node.js library?
- 'node' to enable Node built-ins like fs.
- 'web' for browser compatibility.
- 'electron' for cross-platform.
Answer
'node' to enable Node built-ins like fs. — The 'node' target ensures Node.js built-ins like fs and path are available and not bundled into the output.