Webpack 5 核心配置与性能优化
Webpack 是现代前端构建工具,配置合理可加速构建和加载。
1. 基础配置
const path = require('path');
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
filename: 'bundle.[contenthash].js',
path: path.resolve(__dirname, 'dist'),
clean: true,
},
module: {
rules: [
{ test: /\.css$/, use: ['style-loader', 'css-loader'] },
{ test: /\.(png|jpg)$/, type: 'asset/resource' },
{ test: /\.js$/, exclude: /node_modules/, use: 'babel-loader' },
],
},
plugins: [
new HtmlWebpackPlugin({ template: './src/index.html' }),
],
optimization: {
splitChunks: { chunks: 'all' },
},
};2. 开发服务器
devServer: {
static: './dist',
hot: true,
port: 3000,
}3. 性能优化
- 使用
cache: { type: 'filesystem' }持久缓存。 - 使用
thread-loader多进程编译。 - 使用
terser-webpack-plugin压缩代码。
Webpack 是前端工程化的基石。
