Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 38 ยท Projects and Practice

Project: A Production-Ready Webpack Config

Project: assemble a complete, production-ready webpack 5 setup with common, dev and prod configs, merging, content hashes, split chunks, CSS extraction, budgets and a config audit.

This project pulls together everything from the course into one realistic setup: a single-page app with JavaScript, CSS and images, a fast development profile and a lean, cache-friendly production profile. You will organize configs into three files, merge them, check them with an automated audit, and review a checklist you can reuse on real projects.

Webpack cannot run on this site, so the project files are read-only listings you can copy to your own machine. The two TryIt blocks are Node.js stand-ins: a config merger that acts like webpack-merge, and an auditor that applies the rules of thumb from earlier lessons to a config object.

Project layout

Text
my-app/
  public/index.html
  src/
    index.js
    bootstrap.js
    styles.css
    pages/
  webpack.common.js
  webpack.dev.js
  webpack.prod.js
  package.json
JSON
{
  "scripts": {
    "start": "webpack serve --config webpack.dev.js",
    "build": "webpack --config webpack.prod.js",
    "analyze": "ANALYZE=1 webpack --config webpack.prod.js"
  },
  "sideEffects": ["*.css"],
  "browserslist": ["defaults", "not dead"]
}

sideEffects lists the CSS files so tree shaking does not drop them. browserslist keeps Babel and CSS tooling from compiling for ancient browsers.

webpack.common.js

Everything that is the same in both environments:

JavaScript
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: { main: './src/index.js' },
  output: {
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/',
    clean: true,
  },
  resolve: {
    extensions: ['.js', '.jsx'],
    alias: { '@': path.resolve(__dirname, 'src') },
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: { presets: [['@babel/preset-env', { modules: false }]], cacheDirectory: true },
        },
      },
      {
        test: /\.(png|jpe?g|gif|svg|webp)$/i,
        type: 'asset',
        parser: { dataUrlCondition: { maxSize: 8 * 1024 } },
        generator: { filename: 'images/[name].[contenthash:8][ext]' },
      },
      {
        test: /\.(woff2?)$/i,
        type: 'asset/resource',
        generator: { filename: 'fonts/[name].[contenthash:8][ext]' },
      },
    ],
  },
  plugins: [new HtmlWebpackPlugin({ template: './public/index.html' })],
};

webpack.dev.js

Speed and feedback:

JavaScript
const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');

module.exports = merge(common, {
  mode: 'development',
  devtool: 'eval-cheap-module-source-map',
  output: { filename: '[name].js' },
  module: {
    rules: [{ test: /\.css$/, use: ['style-loader', 'css-loader'] }],
  },
  devServer: {
    port: 3000,
    hot: true,
    historyApiFallback: true,
    static: 'public',
    proxy: [{ context: ['/api'], target: 'http://localhost:8080' }],
  },
  cache: { type: 'filesystem' },
});

webpack.prod.js

Size, caching and safety:

JavaScript
const { merge } = require('webpack-merge');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const common = require('./webpack.common.js');

module.exports = merge(common, {
  mode: 'production',
  devtool: 'source-map',
  output: {
    filename: '[name].[contenthash:8].js',
    chunkFilename: '[name].[contenthash:8].chunk.js',
  },
  module: {
    rules: [{ test: /\.css$/, use: [MiniCssExtractPlugin.loader, 'css-loader'] }],
  },
  plugins: [
    new MiniCssExtractPlugin({ filename: '[name].[contenthash:8].css' }),
    process.env.ANALYZE && new BundleAnalyzerPlugin({ analyzerMode: 'static', openAnalyzer: false }),
  ].filter(Boolean),
  optimization: {
    minimizer: ['...', new CssMinimizerPlugin()],
    runtimeChunk: 'single',
    moduleIds: 'deterministic',
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        vendors: { test: /[\\/]node_modules[\\/]/, name: 'vendors', priority: 10 },
      },
    },
  },
  performance: { hints: 'warning', maxEntrypointSize: 300_000, maxAssetSize: 250_000 },
});

Each choice comes from an earlier lesson: content hashes and runtime chunk, split chunks, minification and source maps, and budgets.

How merging works

webpack-merge concatenates arrays (such as module.rules and plugins) and deep-merges objects, with the later config winning on scalar values. That is why the CSS rule can differ per environment while the Babel rule is shared.

Node.js Stand-in: merge common and environment configs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The merged result has two rules (Babel and CSS), and the output object contains both path and filename.

Audit the config automatically

A review checklist is more useful when a script can run it. This stand-in audits a config object against the rules from this course. Adapt it to your own team's standards and run the real equivalent on your final config object in CI.

Node.js Stand-in: audit a production config

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Final checklist

  • Mode and environment: separate dev and prod configs, NODE_ENV set by the script.
  • Caching: contenthash everywhere, runtime chunk, deterministic ids, long cache headers on assets and no-cache on HTML.
  • Size: splitChunks: 'all', lazy routes with dynamic imports, sideEffects set, ES modules preserved, a budget.
  • Debugging: source maps uploaded to your error tracker, not served publicly if you want to keep sources private.
  • Safety: no secrets in DefinePlugin or VITE_-style variables; everything defined in client code is public.
  • Developer experience: filesystem cache, HMR, a clean proxy to the backend.
  • Verification: build in CI, run the analyzer on demand, and test the production build, not just the dev server.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In webpack-merge, what happens to module.rules arrays from two configs?

    Arrays such as rules and plugins are concatenated, so shared rules stay and environment rules are added.
  2. 2. Why is the CSS rule different between dev and prod?

    style-loader supports quick updates in development, while extracted CSS files are cacheable and do not block on JavaScript.
  3. 3. Which of these must never be put into DefinePlugin or public env variables?

    Values defined for client code end up in the shipped bundle and are visible to every user.
  4. 4. What is the benefit of auditing the config in CI?

    Automated checks keep important settings from being changed or forgotten as the config evolves.

Summary

  • Split the config into common, dev and prod files and merge them.
  • Development favours fast feedback; production favours small, hashed, cacheable files.
  • Automate review of the config and of the output size.
  • Never expose secrets through build-time constants.

Next: Project: A Lazy-Loaded Dashboard