Webpack Production Builds
A production build has three goals beyond "it works": small (minified, tree-shaken, split so the first page loads little), cacheable (file names change only when content changes), and observable (source maps and stats you can inspect). This lesson builds a small React app the way a production Webpack config would.
The config
// webpack.config.js
import path from 'node:path';
export default {
mode: 'production',
entry: './src/index.js',
output: {
path: path.resolve('dist'),
filename: '[name].[contenthash:8].js', // long-term caching
chunkFilename: '[name].[contenthash:8].js',
clean: true,
},
optimization: {
runtimeChunk: 'single', // webpack's runtime in its own small file
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: { test: /[\\/]node_modules[\\/]/, name: 'vendor' }, // libraries change rarely
},
},
},
devtool: 'source-map',
performance: { hints: 'warning', maxEntrypointSize: 250_000, maxAssetSize: 250_000 },
};| Setting | Why |
|---|---|
[contenthash:8] |
the name is derived from the file's content: unchanged files keep their URL and stay cached |
runtimeChunk: 'single' |
the runtime holds the chunk-to-file map, which changes on every build; isolating it keeps the other hashes stable |
splitChunks.cacheGroups.vendor |
all node_modules code in one vendor chunk, cached across app deployments |
performance |
warn when an entry or asset is too big for a fast first load |
Building it
mkdir -p app/src && cd app
npm init -y > /dev/null && npm pkg set type=module
npm install react@19.3.1 react-dom@19.3.1 > /dev/null && npm install -D webpack@5.112.2 webpack-cli@7.2.3 > /dev/null 2>&1
cat > src/index.js <<'JS'
import { createElement as h, useState } from 'react';
import { createRoot } from 'react-dom/client';
function App() {
const [report, setReport] = useState(null);
const open = async () => setReport((await import(/* webpackChunkName: "report" */ './report.js')).render());
return h('main', null, h('h1', null, 'Shop'), h('button', { onClick: open }, 'Show report'), report);
}
createRoot(document.getElementById('root')).render(h(App));
JS
cat > src/report.js <<'JS'
export const render = () => 'Sales report: 42 orders';
JS
cat > webpack.config.js <<'JS'
import path from 'node:path';
export default {
mode: 'production',
entry: './src/index.js',
output: { path: path.resolve('dist'), filename: '[name].[contenthash:8].js', chunkFilename: '[name].[contenthash:8].js', clean: true },
optimization: {
runtimeChunk: 'single',
splitChunks: { chunks: 'all', cacheGroups: { vendor: { test: /[\\/]node_modules[\\/]/, name: 'vendor' } } },
},
devtool: 'source-map',
performance: { hints: 'warning', maxEntrypointSize: 250000, maxAssetSize: 250000 },
};
JS
npx webpack 2>&1 | grep -E '^asset|^Entrypoint|^WARNING|^ [a-z]|compiled'
ls dist | grep -v '\.map$\|LICENSE'asset vendor.781a57d6.js 213 KiB [emitted] [immutable] [minimized] (name: vendor) (id hint: vendor) 2 related assets
asset runtime.fac29ef7.js 3.03 KiB [emitted] [immutable] [minimized] (name: runtime) 1 related asset
asset main.d00fb4d8.js 495 bytes [emitted] [immutable] [minimized] (name: main) 1 related asset
asset report.11a4cdf4.js 190 bytes [emitted] [immutable] [minimized] (name: report) 1 related asset
Entrypoint main 217 KiB (1010 KiB) = runtime.fac29ef7.js 3.03 KiB vendor.781a57d6.js 213 KiB main.d00fb4d8.js 495 bytes 3 auxiliary assets
modules by path ./node_modules/ 648 KiB
modules by path ./src/*.js 497 bytes
webpack 5.112.2 compiled successfully in 2052 ms
main.d00fb4d8.js
report.11a4cdf4.js
runtime.fac29ef7.js
vendor.781a57d6.js
Reading the result:
- vendor.*.js holds React and react-dom; it's most of the bytes. It only changes when you upgrade React.
- main.*.js is your app code: tiny, and the file that changes on most deployments.
- runtime.*.js is Webpack's loader and chunk map.
- report.*.js is the lazy chunk from
import(), downloaded only when someone clicks the button. ThewebpackChunkNamecomment gave it a readable name. - The entry point (runtime + vendor + main) is what the browser must load first. Its size is what the performance hint measures: 217 KiB here, just under the 250 000-byte budget, so no warning. Lower
maxEntrypointSizeand the build printsWARNING in entrypoint size limit(it fails only withhints: 'error'). The size in brackets,(1010 KiB), adds the three auxiliary assets: source maps and the extracted licence file.
Hashes that only change when they should
Change one line of app code and rebuild: only the files that really changed get new names.
mkdir -p app/src && cd app
npm init -y > /dev/null && npm pkg set type=module
npm install react@19.3.1 react-dom@19.3.1 > /dev/null && npm install -D webpack@5.112.2 webpack-cli@7.2.3 > /dev/null 2>&1
cat > src/index.js <<'JS'
import { createElement as h } from 'react';
import { createRoot } from 'react-dom/client';
createRoot(document.getElementById('root')).render(h('h1', null, 'Shop v1'));
JS
cat > webpack.config.js <<'JS'
import path from 'node:path';
export default {
mode: 'production',
entry: './src/index.js',
output: { path: path.resolve('dist'), filename: '[name].[contenthash:8].js', clean: true },
optimization: { runtimeChunk: 'single', splitChunks: { chunks: 'all', cacheGroups: { vendor: { test: /[\\/]node_modules[\\/]/, name: 'vendor' } } } },
performance: { hints: false },
};
JS
npx webpack > /dev/null && ls dist > before.txt
sed -i 's/Shop v1/Shop v2/' src/index.js
npx webpack > /dev/null && ls dist > after.txt
diff before.txt after.txt
echo "unchanged: $(comm -12 before.txt after.txt | tr '\n' ' ')"1c1
< main.f8c01dce.js
---
> main.4ba609fe.js
unchanged: runtime.ece82806.js vendor.c6120742.js vendor.c6120742.js.LICENSE.txt
Only main got a new hash; returning visitors re-download a few hundred bytes instead of the whole React bundle. Webpack 5's defaults (moduleIds: 'deterministic', chunkIds: 'deterministic' in production) are what keep the vendor hash stable when unrelated modules change.
What mode: 'production' turns on
| Optimisation | Setting | Effect |
|---|---|---|
| minification | optimization.minimize: true (Terser via the minimizer plugin) |
renames, removes whitespace and dead code |
| tree shaking | usedExports, sideEffects: true |
unused exports removed, side-effect-free modules skipped |
| scope hoisting | concatenateModules: true |
modules merged into one scope where possible |
| stable ids | moduleIds/chunkIds: 'deterministic' |
hashes don't churn |
process.env.NODE_ENV |
optimization.nodeEnv: 'production' |
libraries drop dev-only code (React's warnings) |
The last one matters a lot for React: the development build of react-dom is several times bigger than the production build, selected by a process.env.NODE_ENV check that Webpack replaces at build time.
Serving the result
An HTML page must reference the hashed names, which change on every relevant build. In practice html-webpack-plugin generates index.html with the right <script> tags (the manifest plugin you wrote is the same idea). Then serve:
- hashed files with
Cache-Control: public, max-age=31536000, immutable; index.htmlwithCache-Control: no-cache, so the newest asset names are always picked up;- source maps either privately (upload them to your error tracker and use
hidden-source-map) or publicly if your code is open.
Test yourself
Why put node_modules code in its own vendor chunk?
- Vendors require it
- Library code changes rarely, so its file stays cached across app deployments
- It makes the code run faster
- To exclude licenses
What does runtimeChunk: 'single' achieve?
- Removes the runtime
- Moves webpack's runtime (with the chunk map that changes every build) into its own file, keeping other hashes stable
- Makes all code one chunk
- Enables HMR
After changing one line in src/index.js, which file got a new name?
- All of them
- Only main.[hash].js
- Only vendor.[hash].js
- None, hashes are random