Webpack 的安装和基本配置方法。
展示 Webpack 的基本配置。
# 全局安装
npm install -g webpack webpack-cli
# 项目安装
npm install --save-dev webpack webpack-cli
// webpack.config.js
const path = require('path');
module.exports = {
// 入口文件
entry: './src/index.js',
// 输出配置
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
// 开发模式
mode: 'development',
// 开发工具
devtool: 'source-map',
// 开发服务器
devServer: {
contentBase: './dist',
port: 3000,
hot: true
}
};
Webpack 的 Loader 配置。
展示常用 Loader 的配置。
// webpack.config.js
module.exports = {
// ... 其他配置
module: {
rules: [
// Babel Loader
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
},
// CSS Loader
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
// SCSS Loader
{
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader']
},
// 图片 Loader
{
test: /\.(png|svg|jpg|gif)$/,
use: ['file-loader']
},
// 字体 Loader
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: ['file-loader']
}
]
}
};
Webpack 的代码分割功能。
展示代码分割的配置。
// webpack.config.js
module.exports = {
// ... 其他配置
optimization: {
splitChunks: {
chunks: 'all',
minSize: 20000,
maxSize: 0,
minChunks: 1,
maxAsyncRequests: 30,
maxInitialRequests: 30,
automaticNameDelimiter: '~',
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
}
}
};
// 动态导入
import(/* webpackChunkName: "lodash" */ 'lodash').then(({ default: _ }) => {
console.log(_.join(['Hello', 'webpack'], ' '));
});
Webpack 的插件配置。
展示常用插件的配置。
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const webpack = require('webpack');
module.exports = {
// ... 其他配置
plugins: [
// 清理输出目录
new CleanWebpackPlugin(),
// 生成 HTML 文件
new HtmlWebpackPlugin({
title: 'Webpack App',
template: './src/index.html'
}),
// 提取 CSS
new MiniCssExtractPlugin({
filename: '[name].[contenthash].css'
}),
// 环境变量
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
}),
// 热更新
new webpack.HotModuleReplacementPlugin()
]
};
Webpack 的构建优化配置。
展示构建优化的配置。
// webpack.config.js
module.exports = {
// ... 其他配置
optimization: {
// 压缩代码
minimize: true,
// 模块标识符
moduleIds: 'deterministic',
// 运行时块
runtimeChunk: 'single',
// 缓存组
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
}
}
}
},
// 解析配置
resolve: {
// 扩展名
extensions: ['.js', '.json', '.jsx'],
// 别名
alias: {
'@': path.resolve(__dirname, 'src')
},
// 模块解析
modules: ['node_modules']
}
};
Webpack 的开发优化配置。
展示开发优化的配置。
// webpack.config.js
module.exports = {
// ... 其他配置
// 开发服务器
devServer: {
contentBase: './dist',
port: 3000,
hot: true,
open: true,
compress: true,
historyApiFallback: true,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
},
// 缓存
cache: {
type: 'filesystem',
buildDependencies: {
config: [__filename]
}
},
// 性能提示
performance: {
hints: 'warning',
maxEntrypointSize: 512000,
maxAssetSize: 512000
}
};
Webpack 的多环境配置。
展示多环境配置的使用。
// webpack.common.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[contenthash].js'
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
})
]
};
// webpack.dev.js
const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');
module.exports = merge(common, {
mode: 'development',
devtool: 'inline-source-map',
devServer: {
contentBase: './dist'
}
});
// webpack.prod.js
const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');
module.exports = merge(common, {
mode: 'production',
devtool: 'source-map'
});
Webpack 的自定义配置。
展示自定义配置的使用。
// webpack.config.js
const path = require('path');
const webpack = require('webpack');
// 自定义插件
class MyPlugin {
apply(compiler) {
compiler.hooks.emit.tapAsync('MyPlugin', (compilation, callback) => {
console.log('MyPlugin is running');
callback();
});
}
}
module.exports = {
// ... 其他配置
plugins: [
new MyPlugin()
],
// 自定义 loader
module: {
rules: [
{
test: /\.my$/,
use: [
{
loader: path.resolve('path/to/loader.js'),
options: {
// loader 选项
}
}
]
}
]
}
};
建议按照章节顺序学习,每完成一个练习后再进行下一个。可以通过实际项目来实践所学知识,特别是性能优化和最佳实践部分。注意 Webpack 的配置非常灵活,需要根据项目需求选择合适的配置方案。