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:
| Type | Webpack 4 | Webpack 5 | Description |
|---|---|---|---|
| CommonJS | ✅ | ✅ | module.exports = {} |
| ES Modules | ⚠️ Limited | ✅ Full | export 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
| Feature | Webpack 4 | Webpack 5 |
|---|---|---|
| Output.clean | ❌ Not available | ✅ Clean dist folder automatically |
| Output.pathinfo | ✅ Default true | ✅ Default false (production) |
| Output.hashFunction | MD4 | MD4 (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 Type | Webpack 4 | Webpack 5 | replacement Module |
|---|---|---|---|
| file-loader | Required | ✅ Alternative | asset/resource |
| url-loader | Required | ✅ Alternative | asset |
| raw-loader | Required | ✅ Alternative | asset/source |
| svg-url-loader | Required | ✅ Alternative | Custom 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
| Plugin | Description | Webpack 4 | Webpack 5 |
|---|---|---|---|
| html-webpack-plugin | Generates HTML files | ✅ | ✅ |
| mini-css-extract-plugin | Extracts CSS to separate files | ✅ | ✅ |
| clean-webpack-plugin | Cleans output directory | ✅ | ✅ |
| terser-webpack-plugin | Minifies JavaScript | ✅ | ✅ |
| filemanager-webpack-plugin | File system operations | ✅ | ✅ |
| module-federation-plugin | Module Federation | ❌ | ✅ |
Webpack 5 Built-in Plugins
Webpack 5 includes several plugins that were external in Webpack 4:
| Plugin | Webpack 4 | Webpack 5 |
|---|---|---|
| asset-plugins | Required | ✅ Built-in |
| module-federation | Required | ✅ Built-in |
| persistent-cache | Required | ✅ 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
| Optimization | development | production |
|---|---|---|
| nodeEnv | 'development' | 'production' |
| debug | true | false |
| moduleIds | 'named' | 'deterministic' |
| chunkIds | 'named' | 'deterministic' |
| optimization.removeAvailableModules | false | true |
| optimization.removeEmptyChunks | false | true |
| optimization.splitChunks | false | true |
| optimization.minimize | false | true |
Development Tools
Source Maps
Source maps help debug compiled code by mapping it back to the original source.
| Option | Webpack 4 | Webpack 5 | Description |
|---|---|---|---|
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
| Feature | Webpack 4 | Webpack 5 |
|---|---|---|
| devServer.static | directory as string | object with directory property |
| devServer.contentBase | ✅ Deprecated | ❌ Removed |
| watchOptions | Direct property | Direct 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
| Feature | Webpack 4 | Webpack 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
| Feature | Webpack 4 | Webpack 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
| Command | Description |
|---|---|
webpack | Run webpack build |
webpack build | Run webpack build (explicit) |
webpack watch | Watch for file changes |
webpack serve | Run webpack-dev-server |
webpack info | Output system information |
webpack configtest | Validate webpack configuration |
Common Flags
| Flag | Description |
|---|---|
--mode development | Set mode to development |
--mode production | Set mode to production |
--config webpack.config.js | Use custom config file |
--entry ./src/index.js | Set entry point |
-o, --output-path ./dist | Set output directory |
-w, --watch | Watch for changes |
--devtool source-map | Set source map option |
--json | Print stats as JSON |
--progress | Show compilation progress |
Configuration Comparison
| Feature | Webpack 4 | Webpack 5 |
|---|---|---|
| --env | String values only | Object values supported |
| --config-node-env | ❌ Not available | ✅ Set process.env.NODE_ENV |
| --analyze | Requires plugin | ✅ Built-in support |
| --info | Basic output | Enhanced output |
Environment Variables
Webpack provides several built-in environment variables:
| Variable | Description |
|---|---|
WEBPACK_SERVE | true if webpack-dev-server is being used |
WEBPACK_BUILD | true if build is being used |
WEBPACK_WATCH | true 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
- Use
file-loader,url-loaderfor assets - Configure caching with
cache-loader - Use
optimization.concatenateModulesfor scope hoisting - Use
ExtractTextPluginfor CSS extraction
Webpack 5
- Use Asset Modules instead of file-loader/url-loader
- Enable
cache.type = 'filesystem'for faster rebuilds - Use built-in Module Federation for micro-frontends
- Use
_magic_commentsfor 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.
