Comprehensive Guide to Webpack: Core Concepts, Configuration, Loaders, and Optimization
This comprehensive, step‑by‑step guide walks developers through Webpack’s core concepts, project setup, configuration files, development server with hot module replacement, essential loaders for CSS, images, Less, and Babel, plus optimization techniques such as JavaScript minification, CSS extraction, and output cleaning.
This article provides a step‑by‑step tutorial on using Webpack for front‑end development. It starts with an overview of Webpack’s core concepts such as module , chunk , bundle , entry , output , mode , loader , and plugin .
Basic setup
Initialize a project and install Webpack:
npm init -y
npm install -D webpack webpack-cliCreate webpack.config.js with a minimal entry and output configuration:
const path = require('path');
module.exports = {
entry: path.resolve(__dirname, 'src/index.js'),
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: './'
}
};Add a simple source file src/index.js :
const a = 12;
const b = 12;
function add(x, y) {
return x + y;
}
const c = add(a, b);
console.log(c);Define a build script in package.json :
{
"scripts": {
"build": "webpack --mode development"
}
}Running npm run build generates dist/bundle.js .
HTML template with html‑webpack‑plugin
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
// ...
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'src/index.html'),
filename: 'webpack.html'
})
]
};Development server
npm install --save-dev webpack-dev-server module.exports = {
// ...
devServer: {
contentBase: path.join(__dirname, 'dist'),
port: '8080',
host: 'localhost'
}
};Start it with:
{
"scripts": {
"dev": "webpack-dev-server --mode development"
}
}Enable Hot Module Replacement (HMR):
devServer: {
// ...
hot: true
};Update the script:
{
"scripts": {
"dev": "webpack-dev-server --mode development --open --hot"
}
}Loaders
CSS loader
npm install --save-dev style-loader css-loader module: {
rules: [
{
test: /.css/,
use: ['style-loader', 'css-loader'],
exclude: /node_modules/,
include: path.resolve(__dirname, 'src')
}
]
}Image loaders (url‑loader & file‑loader)
npm install --save-dev url-loader file-loader module: {
rules: [
{
test: /\.(gif|jpg|png|bmp|eot|woff|woff2|ttf|svg)/,
use: [{
loader: 'url-loader',
options: { limit: 8192, outputPath: 'images' }
}]
}
]
}Webpack 5 can replace these with built‑in asset modules:
module: {
rules: [
{
test: /\.(jpe?g|png|gif)$/i,
type: 'asset',
generator: { filename: '[name][hash:8][ext]' },
parser: { dataUrlCondition: { maxSize: 50 * 1024 } }
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/i,
type: 'asset',
generator: { filename: '[name][hash:8][ext]' },
parser: { dataUrlCondition: { maxSize: 10 * 1024 } }
}
]
}Less loader
npm install --save-dev less less-loader module: {
rules: [
{
test: /.less/,
use: ['style-loader', 'css-loader', 'less-loader'],
exclude: /node_modules/,
include: path.resolve(__dirname, 'src')
}
]
}Babel loader for ES6/JSX
npm install --save-dev @babel/core babel-loader @babel/preset-env @babel/preset-react @babel/plugin-proposal-decorators module: {
rules: [
{
test: /.jsx?$/,
use: [{
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/react'],
plugins: [[require('@babel/plugin-proposal-decorators'), { legacy: true }]]
}
}],
include: path.resolve(__dirname, 'src'),
exclude: /node_modules/
}
]
}Optimization
JS minification (Webpack 5 uses TerserWebpackPlugin by default):
optimization: {
minimizer: [
new TerserWebpackPlugin({
terserOptions: {
compress: { drop_console: true, drop_debugger: true }
}
})
]
}Extract CSS into separate files:
npm install --save-dev mini-css-extract-plugin const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
// ...
module: {
rules: [
{
test: /.css/,
use: [{ loader: MiniCssExtractPlugin.loader }, 'css-loader']
},
{
test: /.less/,
use: [{ loader: MiniCssExtractPlugin.loader }, 'css-loader', 'less-loader']
}
]
},
plugins: [
new MiniCssExtractPlugin({ filename: 'css/[name].css' })
]
};CSS minification:
npm install --save-dev optimize-css-assets-webpack-plugin const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
module.exports = {
// ...
optimization: {
minimizer: [new OptimizeCssAssetsWebpackPlugin()]
}
};Clean the output directory before each build:
npm install --save-dev clean-webpack-plugin const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
// ...
plugins: [new CleanWebpackPlugin()]
};The article concludes with a link to the full demo repository ( [email protected]:AdolescentJou/webpack4-base-demo.git ) and author information. It emphasizes that although Webpack 4 is aging, many companies still rely on it, and the guide aims to help developers master its configuration and optimization.
Tencent Cloud Developer
Official Tencent Cloud community account that brings together developers, shares practical tech insights, and fosters an influential tech exchange community.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.