Build for production with webpack

Learn production build techniques, including minification, CSS extraction, environment variables, separate environment configurations, and bundle analysis.

🎯 Introduction

This article explains how to create production builds with webpack so your frontend project is smaller, faster, and easier to organize. Production builds involve more than bundling: minification, environment variables, environment-specific configurations, and bundle analysis all contribute to performance and maintainability.


🛠️ Minify JavaScript with TerserPlugin

JavaScript file size directly affects page loading speed. TerserPlugin, webpack's default JavaScript minifier, can significantly reduce the size of your JavaScript files.

const TerserPlugin = require('terser-webpack-plugin');

module.exports = {
    mode: 'production',
    optimization: {
        minimize: true,
        minimizer: [
            new TerserPlugin({
                terserOptions: {
                    compress: {
                        drop_console: true, // Remove console calls
                    },
                },
            }),
        ],
    },
};
drop_console: true removes console calls, including console.log, helping prevent debug logs from appearing in production.

💅 Minify CSS with css-minimizer-webpack-plugin

Minifying CSS also reduces transfer time. css-minimizer-webpack-plugin minifies the CSS files extracted by MiniCssExtractPlugin.

const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');

module.exports = {
    mode: 'production',
    optimization: {
        minimizer: [
            '...', // Keep the default JavaScript minimizer
            new CssMinimizerPlugin(),
        ],
    },
};
Include '...' to retain webpack's default JavaScript minimizer; otherwise, this configuration only minifies CSS.

🎨 Extract CSS into separate files with MiniCssExtractPlugin

When CSS is bundled into JavaScript, it cannot be loaded and cached independently. MiniCssExtractPlugin extracts it into separate files that browsers can load in parallel.

const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
    module: {
        rules: [
            {
                test: /\.css$/i,
                use: [
                    MiniCssExtractPlugin.loader, // Extract CSS
                    'css-loader',
                ],
            },
        ],
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: '[name].[contenthash].css', // Add a content hash for caching
        }),
    ],
};
Use [contenthash] in production so changed CSS gets a new filename and browsers do not reuse an outdated cached file.

🌿 Set environment variables with DefinePlugin, .env files, and cross-env

Frontend applications often need different settings for different environments. webpack's DefinePlugin injects values into the build, while .env files and cross-env scripts help manage environment settings across platforms.

1. Use DefinePlugin

const webpack = require('webpack');

module.exports = {
    plugins: [
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
            'process.env.API_URL': JSON.stringify(process.env.API_URL),
        }),
    ],
};

2. Manage variables with .env files

Create .env.production and .env.development in the project root with values for each environment.

# .env.production
API_URL=https://api.example.com

3. Set variables across platforms with cross-env

In your package.json scripts:

"scripts": {
  "build:prod": "cross-env NODE_ENV=production webpack --config webpack.prod.js",
  "build:dev": "cross-env NODE_ENV=development webpack --config webpack.dev.js"
}
cross-env handles the differences in environment variable syntax between Windows and Linux/macOS.

🌍 Separate environment configurations (webpack.prod.js, webpack.dev.js)

A common approach is to separate production and development settings into webpack.prod.js and webpack.dev.js, then combine them with shared settings using webpack-merge.

webpack.common.js
module.exports = {
    entry: './src/index.js',
    module: {
        /* Shared loaders */
    },
    plugins: [
        /* Shared plugins */
    ],
};
webpack.prod.js
const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');

module.exports = merge(common, {
    mode: 'production',
    module: {
        rules: [
            {
                test: /\.css$/i,
                use: [MiniCssExtractPlugin.loader, 'css-loader'],
            },
        ],
    },
    plugins: [new MiniCssExtractPlugin({ filename: '[name].[contenthash].css' })],
    optimization: {
        minimize: true,
        minimizer: [new TerserPlugin(), new CssMinimizerPlugin()],
    },
});
Development configurations typically enable devtool and HMR and avoid minification to make debugging easier.

📊 Analyze build output with Webpack Bundle Analyzer

Understanding how much space each part of a bundle occupies helps guide optimization. webpack-bundle-analyzer generates a visual report of your build output.

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = {
    plugins: [
        new BundleAnalyzerPlugin({
            analyzerMode: 'static', // Generate a static HTML report
            openAnalyzer: false, // Do not open the browser automatically
            reportFilename: 'bundle-report.html',
        }),
    ],
};

After building, open bundle-report.html to see each module's contribution to the bundle size and identify optimization opportunities.

For large dependencies, consider loading on demand, serving assets through a CDN, or switching to a smaller library.

❓ Questions and answers

Q1: Why extract CSS into separate files?

Browsers can load separate CSS files in parallel and cache them independently, improving rendering and reducing repeated downloads.

Q2: How do DefinePlugin and .env differ?

DefinePlugin is webpack's built-in plugin for defining global constants. A .env file stores environment variables; a separate tool typically reads it and passes its values to DefinePlugin.

Q3: What should I do if the bundle is too large?

Inspect its size distribution with webpack-bundle-analyzer, then apply strategies such as code splitting and loading on demand.


🧪 Exercises

Exercise 1: Configure production minification

Complete the following configuration to minify JavaScript and CSS and extract CSS in production.

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

module.exports = merge(common, {
    mode: 'production',
    // Add JavaScript and CSS minification and CSS extraction
});

Exercise 2: Configure environment-specific variables

Use DefinePlugin and a .env file to create a simple production configuration that makes process.env.API_URL available in application code.

// webpack.prod.js
const webpack = require('webpack');

module.exports = {
    // Add environment variable injection
};

🎉 You now understand production minification, CSS extraction, environment-specific configuration, and bundle analysis with webpack! Keep practicing these techniques to improve your frontend builds.