User Manual

This manual covers the core functionality of webpack, including configuration options, CLI usage, and best practices for both Webpack 4 and Webpack 5.

Configuration

Webpack is configured through a JavaScript file named webpack.config.js by default. This file exports a configuration object that tells webpack how to build your project.

Basic Configuration

// Webpack 4 / Webpack 5 (CommonJS)
const path = require('path');

module.exports = {
  mode: 'production',
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
};
// Webpack 5 (ES Modules)
import path from 'node:path';

export default {
  mode: 'production',
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(import.meta.dirname, 'dist'),
  },
};

Configuration Types

Webpack supports multiple configuration file types:

TypeWebpack 4Webpack 5Description
CommonJS✅✅module.exports = {}
ES Modules⚠️ Limited✅ Fullexport default {}
TypeScript⚠️ With ts-node✅ Native.ts files
Multiple Configs✅✅Array of configurations

Entry Points

The entry point tells webpack where to start building the dependency graph.

Single Entry

// Webpack 4 & 5
module.exports = {
  entry: './src/index.js',
};

Multiple Entries

// Webpack 4 & 5
module.exports = {
  entry: {
    main: './src/index.js',
    vendor: './src/vendor.js',
  },
};

Dynamic Entries

// Webpack 4 & 5
module.exports = {
  entry: {
    page1: './src/page1.js',
    page2: './src/page2.js',
  },
};

Entry Object with Arrays

// Webpack 4 & 5
module.exports = {
  entry: {
    app: ['./src/index.js', './src/another.js'],
  },
};

Output

The output configuration tells webpack where to emit the bundles it creates.

Basic Output

// Webpack 4 & 5
module.exports = {
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
};

Named Output with [name]

// Webpack 4 & 5
module.exports = {
  entry: {
    main: './src/index.js',
    another: './src/another.js',
  },
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
};

Output with [hash] and [chunkhash]

// Webpack 4 & 5
module.exports = {
  output: {
    filename: '[name].[contenthash].js',
    path: path.resolve(__dirname, 'dist'),
    clean: true, // Webpack 5 only - cleans dist folder
  },
};

Configuration Comparison

FeatureWebpack 4Webpack 5
Output.clean❌ Not available✅ Clean dist folder automatically
Output.pathinfo✅ Default true✅ Default false (production)
Output.hashFunctionMD4MD4 (default), md4, xxHash64, bubblehash
Output.module❌ Not available✅ Output as ES module
Output.environment❌ Not available✅ ES module support settings

Loaders

Loaders allow webpack to process more than just JavaScript files.

Basic Loader Configuration

// Webpack 4 & 5
module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: 'babel-loader',
      },
    ],
  },
};

Loader Options

// Webpack 4 & 5
module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env'],
            plugins: ['@babel/plugin-transform-runtime'],
          },
        },
      },
    ],
  },
};

Asset Modules (Webpack 5 only)

Webpack 5 introduced Asset Modules as a replacement for file-loader, url-loader, and raw-loader.

// Webpack 5
module.exports = {
  module: {
    rules: [
      // replaced file-loader
      {
        test: /\.(png|jpg|gif)$/,
        type: 'asset/resource',
      },
      // replaced url-loader
      {
        test: /\.svg$/,
        type: 'asset',
        parser: {
          dataUrlCondition: {
            maxSize: 8 * 1024, // 8kb
          },
        },
      },
      // replaced raw-loader
      {
        test: /\.txt$/,
        type: 'asset/source',
      },
    ],
  },
};

Loader Comparison

Loader TypeWebpack 4Webpack 5replacement Module
file-loaderRequired✅ Alternativeasset/resource
url-loaderRequired✅ Alternativeasset
raw-loaderRequired✅ Alternativeasset/source
svg-url-loaderRequired✅ AlternativeCustom processing

Plugins

Plugins perform a wider range of tasks than loaders, from bundle optimization to environment variable injection.

Basic Plugin Configuration

// Webpack 4 & 5
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');

module.exports = {
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production'),
    }),
  ],
};

Common Plugins

PluginDescriptionWebpack 4Webpack 5
html-webpack-pluginGenerates HTML files✅✅
mini-css-extract-pluginExtracts CSS to separate files✅✅
clean-webpack-pluginCleans output directory✅✅
terser-webpack-pluginMinifies JavaScript✅✅
filemanager-webpack-pluginFile system operations✅✅
module-federation-pluginModule Federation❌✅

Webpack 5 Built-in Plugins

Webpack 5 includes several plugins that were external in Webpack 4:

PluginWebpack 4Webpack 5
asset-pluginsRequired✅ Built-in
module-federationRequired✅ Built-in
persistent-cacheRequired✅ Built-in

Mode

Webpack provides three built-in mode options: development, production, and none.

// Webpack 4 & 5
module.exports = {
  mode: 'development', // or 'production' or 'none'
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
};

Mode-Specific Optimizations

Optimizationdevelopmentproduction
nodeEnv'development''production'
debugtruefalse
moduleIds'named''deterministic'
chunkIds'named''deterministic'
optimization.removeAvailableModulesfalsetrue
optimization.removeEmptyChunksfalsetrue
optimization.splitChunksfalsetrue
optimization.minimizefalsetrue

Development Tools

Source Maps

Source maps help debug compiled code by mapping it back to the original source.

OptionWebpack 4Webpack 5Description
eval✅✅Fastest, wraps in eval()
cheap-eval-source-map✅✅Good for development
cheap-module-eval-source-map✅✅Preserves original source
source-map✅✅Best quality, slowest
hidden-source-map✅✅Not referenced in bundle
eval-source-map✅✅Works with eval()

Webpack Dev Server

Webpack Dev Server provides a development server with live reloading.

// Webpack 4 & 5
const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  devServer: {
    static: {
      directory: path.join(__dirname, 'public'),
    },
    port: 9000,
    hot: true,
  },
};

Configuration Comparison

FeatureWebpack 4Webpack 5
devServer.staticdirectory as stringobject with directory property
devServer.contentBase✅ Deprecated❌ Removed
watchOptionsDirect propertyDirect property
server❌ Not available✅ New server configuration

Code Splitting

Webpack can split your code into multiple bundles for better performance.

Dynamic Imports (Webpack 4 & 5)

// Webpack 4 & 5
button.addEventListener('click', () => {
  import('./module').then((module) => {
    module.default();
  });
});

Magic Comments (Webpack 4 & 5)

// Webpack 4 & 5
import(
  /* webpackChunkName: "my-chunk" */
  /* webpackMode: "lazy" */
  './module'
).then((module) => {
  module.default();
});

SplitChunks Configuration

// Webpack 4 & 5
module.exports = {
  optimization: {
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all',
        },
      },
    },
  },
};

Configuration Comparison

FeatureWebpack 4Webpack 5
optimization.splitChunks.cacheGroups✅✅
optimization.chunkGroups❌ Not available✅ Available
optimization.moduleConcatenation✅ (Optimization.concatenateModules)✅ (Optimization.concatenateModules)
fetchPriority❌ Not available✅ Available for import()

Module Federation (Webpack 5 only)

Module Federation is a new feature in Webpack 5 that allows sharing code between different builds at runtime.

Host Configuration

// Webpack 5 - Host application
const ModuleFederationPlugin = require('webpack').container
  .ModuleFederationPlugin;

module.exports = {
  plugins: [
    new ModuleFederationPlugin({
      name: 'host',
      filename: 'remoteEntry.js',
      exposes: {
        './Button': './src/Button',
      },
      remotes: {
        remote: 'remote@http://localhost:3002/remoteEntry.js',
      },
      shared: ['react', 'react-dom'],
    }),
  ],
};

Remote Configuration

// Webpack 5 - Remote application
const ModuleFederationPlugin = require('webpack').container
  .ModuleFederationPlugin;

module.exports = {
  plugins: [
    new ModuleFederationPlugin({
      name: 'remote',
      filename: 'remoteEntry.js',
      exposes: {
        './Button': './src/Button',
      },
      shared: ['react', 'react-dom'],
    }),
  ],
};

This feature is not available in Webpack 4 and requires third-party plugins for similar functionality.

Performance

Webpack provides several options to improve build performance.

Performance Hints

// Webpack 4 & 5
module.exports = {
  performance: {
    hints: 'warning', // or 'error' or false
    maxAssetSize: 200000,
    maxEntrypointSize: 400000,
  },
};

Cache Configuration

// Webpack 4 - requiring external plugin
const FileSystemCache = require('fs-cache');

// Webpack 5 - built-in
module.exports = {
  cache: {
    type: 'filesystem', // new in Webpack 5
    cacheDirectory: path.resolve(__dirname, '.webpack_cache'),
  },
};

Configuration Comparison

FeatureWebpack 4Webpack 5
cache.type❌ Not available✅ 'memory' or 'filesystem'
buildDependencies❌ Not available✅ Track config file changes
managedPaths❌ Not available✅ Optimize caching on macOS/Linux

CLI Reference

Basic Commands

CommandDescription
webpackRun webpack build
webpack buildRun webpack build (explicit)
webpack watchWatch for file changes
webpack serveRun webpack-dev-server
webpack infoOutput system information
webpack configtestValidate webpack configuration

Common Flags

FlagDescription
--mode developmentSet mode to development
--mode productionSet mode to production
--config webpack.config.jsUse custom config file
--entry ./src/index.jsSet entry point
-o, --output-path ./distSet output directory
-w, --watchWatch for changes
--devtool source-mapSet source map option
--jsonPrint stats as JSON
--progressShow compilation progress

Configuration Comparison

FeatureWebpack 4Webpack 5
--envString values onlyObject values supported
--config-node-env❌ Not available✅ Set process.env.NODE_ENV
--analyzeRequires plugin✅ Built-in support
--infoBasic outputEnhanced output

Environment Variables

Webpack provides several built-in environment variables:

VariableDescription
WEBPACK_SERVEtrue if webpack-dev-server is being used
WEBPACK_BUILDtrue if build is being used
WEBPACK_WATCHtrue if watch is being used

Usage Example

// Webpack 4 & 5
module.exports = (env, argv) => {
  return {
    mode: argv.mode || 'development',
    devServer: argv.WEBPACK_SERVE ? {
      static: './dist',
    } : undefined,
  };
};

Best Practices

Configuration Organization

// Webpack 4 & 5 - Base configuration
const path = require('path');

module.exports = (env, argv) => {
  const isProduction = argv.mode === 'production';

  return {
    mode: argv.mode || 'development',
    entry: './src/index.js',
    output: {
      filename: isProduction ? '[name].[contenthash].js' : '[name].js',
      path: path.resolve(__dirname, 'dist'),
      clean: isProduction, // Webpack 5 only
    },
    module: {
      rules: [
        {
          test: /\.css$/,
          use: ['style-loader', 'css-loader'],
        },
      ],
    },
    plugins: [
      // Production-only plugins
      ...(isProduction ? [] : []),
    ],
    optimization: {
      minimize: isProduction,
    },
  };
};

Version-Specific Best Practices

Webpack 4

  1. Use file-loader, url-loader for assets
  2. Configure caching with cache-loader
  3. Use optimization.concatenateModules for scope hoisting
  4. Use ExtractTextPlugin for CSS extraction

Webpack 5

  1. Use Asset Modules instead of file-loader/url-loader
  2. Enable cache.type = 'filesystem' for faster rebuilds
  3. Use built-in Module Federation for micro-frontends
  4. Use _magic_comments for import() optimization

Migration from Webpack 4 to Webpack 5

Step 1: Update Node.js

Webpack 5 requires Node.js 10.13.0 or later:

# Check your version
node -v

# Update if needed
nvm install 14
nvm use 14

Step 2: Replace Loaders with Asset Modules

Webpack 4:

{
  test: /\.(png|jpg|gif)$/,
  use: 'file-loader'
}

Webpack 5:

{
  test: /\.(png|jpg|gif)$/,
  type: 'asset/resource'
}

Step 3: Enable Persistent Caching

Webpack 4: Requires external plugin Webpack 5: Built-in

cache: {
  type: 'filesystem',
},

Step 4: Update CSS Extraction

Webpack 4:

npm install extract-text-webpack-plugin --save-dev

Webpack 5:

npm install mini-css-extract-plugin --save-dev

Step 5: Update Plugin Usage

Some plugins have been replaced or updated in Webpack 5. Check plugin documentation for compatibility.