欢迎来到程序员中文网!

首页 Linux Mysql C++ Python PHP JavaScript 资源下载 动态 开源推荐
我要投稿 投诉建议

Webpack 5 核心配置与优化

时间:2026年08月12日 04:50:02 浏览:0

基本配置


const path = require('path');

module.exports = {
mode: 'production', // 或 'development'
entry: './src/index.js',
output: {
filename: 'bundle.[contenthash].js',
path: path.resolve(__dirname, 'dist'),
clean: true, // 清空 dist
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|jpg)$/,
type: 'asset/resource',
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: { presets: ['@babel/preset-env'] },
},
},
],
},
plugins: [
new HtmlWebpackPlugin({ template: './src/index.html' }),
new MiniCssExtractPlugin(),
],
optimization: {
splitChunks: {
chunks: 'all', // 提取第三方库
},
},
};

开发服务器


npm install --save-dev webpack-dev-server

配置 devServer


devServer: {
static: './dist',
hot: true,
port: 3000,
}

性能优化



  • 使用 cache: { type: 'filesystem' } 持久缓存

  • 使用 thread-loader 多进程编译

  • 使用 terser-webpack-plugin 压缩代码


Webpack 是现代前端工程化的基石。