基本配置
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 是现代前端工程化的基石。
