Getting started

Introduction

Webpack bundles JavaScript, CSS, and other assets into files a browser can load. This reference targets webpack 5 and webpack-cli 7.

Install

npm install --save-dev webpack webpack-cli

webpack is the library; webpack-cli provides the webpack command.

See: Installation

Config file

webpack.config.js

const path = require('node:path')

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[contenthash].js',
    clean: true
  }
}

output.path must be absolute. Name the file webpack.config.mjs, or set "type": "module" in package.json, to use export default.

See: Configuration

CLI

CommandDescription
webpackBuild once
webpack --mode productionProduction build
webpack --watchRebuild on change
webpack serveStart the dev server
webpack configtestValidate the config

See: CLI

Config anatomy

Entry

module.exports = {
  entry: {
    app: './src/app.js',
    admin: './src/admin.js'
  }
}

An entry can also be an array (bundled together) or an object with import and dependOn, which shares modules between chunks.

See: Entry points

Output

output: {
  path: path.resolve(__dirname, 'dist'),
  filename: '[name].[contenthash:8].js',
  chunkFilename: '[name].[contenthash:8].js',
  assetModuleFilename: 'assets/[hash][ext][query]',
  publicPath: '/'
}

Filename tokens

TokenBecomes
[name]Entry or chunk name
[contenthash]Hash of this file's contents
[fullhash]Hash of the whole build
[chunkhash]Hash of the chunk
[id]Chunk ID
[ext]Extension, with the dot
[query]Query string, with the ?

output.clean empties the output directory before each build.

See: Output

Mode

module.exports = {
  mode: 'production'
}

mode is shorthand for three defaults:

mode: 'development'  // => NODE_ENV=development, devtool: 'eval'
mode: 'production'   // => NODE_ENV=production, minified
mode: 'none'         // => no defaults, NODE_ENV untouched

Production mode also turns on tree shaking and deterministic module IDs. Never hardcode the mode twice; read it from an env var.

See: Mode

Plugins

const webpack = require('webpack')

module.exports = {
  plugins: [
    new webpack.DefinePlugin({
      __DEV__: JSON.stringify(true)
    }),
    new webpack.ProgressPlugin()
  ]
}

Plugins hook into the compiler; most are classes you instantiate with new. Since 5.109 webpack writes HTML itself (experiments.html), retiring html-webpack-plugin.

See: Plugins

Loaders and assets

Babel

npm install --save-dev babel-loader @babel/core
npm install --save-dev @babel/preset-env

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: 'babel-loader'
      }
    ]
  }
}

babel.config.js

module.exports = {
  presets: [
    ['@babel/preset-env', { targets: 'defaults' }]
  ]
}

Loaders run right to left, so the last entry in use transforms first.

See: babel-loader

CSS

npm install --save-dev style-loader css-loader
module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader']
      }
    ]
  }
}

css-loader resolves @import and url(); style-loader injects the result with a <style> tag. Use mini-css-extract-plugin to emit a real .css file instead.

See: css-loader

PostCSS

{
  test: /\.css$/i,
  use: [
    'style-loader',
    'css-loader',
    'postcss-loader'
  ]
}

postcss.config.js

module.exports = {
  plugins: {
    'postcss-preset-env': {}
  }
}

postcss-preset-env replaces the retired postcss-cssnext, and covers autoprefixing and modern syntax.

See: postcss-loader

Asset modules

module.exports = {
  module: {
    rules: [
      { test: /\.png$/i, type: 'asset/resource' },
      { test: /\.svg$/i, type: 'asset/inline' },
      { test: /\.txt$/i, type: 'asset/source' },
      {
        test: /\.jpg$/i,
        type: 'asset',
        parser: { dataUrlCondition: { maxSize: 8192 } }
      }
    ]
  }
}

Types

TypeEmitsReplaces
asset/resourceA file, exporting its URLfile-loader
asset/inlineA data URIurl-loader
asset/sourceThe raw sourceraw-loader
asset/bytesA Uint8Arraynone
assetInline under maxSize, else a fileurl-loader

Asset modules are built in, so no loader is needed for images or fonts.

See: Asset modules

Dev server

Setup

npm install --save-dev webpack-dev-server
module.exports = {
  devServer: {
    static: './public',
    port: 8080,
    hot: true,
    historyApiFallback: true
  }
}

Run it with npx webpack serve. static replaces the removed contentBase option.

See: DevServer

Proxy

module.exports = {
  devServer: {
    proxy: [
      {
        context: ['/api'],
        target: 'http://localhost:3000'
      }
    ]
  }
}

Requests to /api go to the backend; the rest are served by webpack. Options come from http-proxy-middleware.

See: devServer.proxy

Caching

Content hashes

module.exports = {
  output: {
    filename: '[name].[contenthash].js',
    chunkFilename: '[name].[contenthash].js'
  },
  optimization: {
    runtimeChunk: 'single'
  }
}

A [contenthash] filename changes only when that file changes. Splitting the runtime into its own chunk stops boilerplate churn from renaming every bundle.

See: Caching

Vendor splitting

optimization: {
  splitChunks: {
    cacheGroups: {
      vendor: {
        test: /[\\/]node_modules[\\/]/,
        name: 'vendors',
        chunks: 'all'
      }
    }
  }
}

Third-party code changes less often than your own, so it deserves its own long-lived bundle.

See: SplitChunksPlugin

Filesystem cache

module.exports = {
  cache: {
    type: 'filesystem',
    buildDependencies: { config: [__filename] }
  }
}

The default cache is in memory, and production mode turns it off. The filesystem cache persists in node_modules/.cache/webpack between runs.

See: cache

Upgrading from v4

Loaders replaced

v4v5
file-loadertype: 'asset/resource'
url-loadertype: 'asset/inline'
raw-loadertype: 'asset/source'
json-loaderBuilt in
babel-polyfillcore-js plus @babel/preset-env

See: Asset modules

Node polyfills

module.exports = {
  resolve: {
    fallback: {
      crypto: require.resolve('crypto-browserify')
    }
  }
}

Webpack 5 stopped bundling polyfills for Node core modules. Add a browser package and route the import with resolve.fallback, or use node-polyfill-webpack-plugin.

See: Shimming

Renamed options

v4v5
devServer.contentBasedevServer.static
devServer.proxy: { '/api': … }devServer.proxy: [{ context, target }]
optimization.namedModulesoptimization.moduleIds: 'named'
optimization.namedChunksoptimization.chunkIds: 'named'
optimization.hashedModuleIdsoptimization.moduleIds: 'deterministic'

NamedModulesPlugin and NamedChunksPlugin were removed along with these options.

Webpack 5 requires Node 10.13+; webpack-dev-server 6 requires Node 22.15+.

See: Migration guide

0 Comments for this cheatsheet. Write yours!