Lesson 14 / 25

Building for different targets

Build Webpack bundles for browsers, Node.js, web workers and Electron by setting the correct target for each runtime.

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?

  • 'web' for browser compatibility.
  • 'electron' for cross-platform.
  • 'node' to enable Node built-ins like fs.
  • 'webworker' to avoid Node built-ins.
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.