Webpack 开发指南
简介
Webpack 是一个现代 JavaScript 应用程序的静态模块打包工具。本文将介绍 Webpack 的核心概念、配置和最佳实践。
基础配置
1. 入口和输出
javascript
// webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[contenthash].js',
clean: true
}
};2. 加载器
javascript
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource'
}
]
}
};高级配置
1. 插件系统
javascript
// webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: './src/index.html'
}),
new MiniCssExtractPlugin({
filename: '[name].[contenthash].css'
})
]
};2. 开发服务器
javascript
// webpack.config.js
module.exports = {
devServer: {
static: './dist',
hot: true,
port: 3000,
open: true,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true
}
}
}
};优化配置
1. 代码分割
javascript
// webpack.config.js
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
},
common: {
name: 'common',
minChunks: 2,
chunks: 'all',
priority: -20
}
}
}
}
};2. 缓存优化
javascript
// webpack.config.js
module.exports = {
output: {
filename: '[name].[contenthash].js',
chunkFilename: '[name].[contenthash].js'
},
optimization: {
moduleIds: 'deterministic',
runtimeChunk: 'single'
}
};高级特性
1. 模块联邦
javascript
// webpack.config.js (Host)
const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin');
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'host',
remotes: {
remote: 'remote@http://localhost:3001/remoteEntry.js'
},
shared: ['react', 'react-dom']
})
]
};
// webpack.config.js (Remote)
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'remote',
filename: 'remoteEntry.js',
exposes: {
'./Button': './src/Button'
},
shared: ['react', 'react-dom']
})
]
};2. 动态导入
javascript
// 使用动态导入
async function loadComponent() {
const { default: Component } = await import('./Component');
return Component;
}
// webpack.config.js
module.exports = {
output: {
chunkFilename: '[name].[contenthash].js'
}
};性能优化
1. 构建优化
javascript
// webpack.config.js
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
terserOptions: {
compress: {
drop_console: true
}
}
})
]
}
};2. 资源优化
javascript
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(png|jpg|gif)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 8192,
name: 'images/[name].[hash:7].[ext]'
}
}
]
}
]
}
};最佳实践
配置管理
- 使用 webpack-merge 管理多环境配置
- 模块化配置文件
- 使用环境变量
开发流程
- 使用 webpack-dev-server
- 实施热更新
- 使用 source maps
构建优化
- 合理使用缓存
- 优化加载器配置
- 使用 tree shaking
常见问题
1. 路径解析
javascript
// webpack.config.js
const path = require('path');
module.exports = {
resolve: {
extensions: ['.js', '.jsx', '.json'],
alias: {
'@': path.resolve(__dirname, 'src'),
'@components': path.resolve(__dirname, 'src/components')
}
}
};2. 环境变量
javascript
// webpack.config.js
const webpack = require('webpack');
module.exports = {
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
})
]
};总结
Webpack 是一个强大的模块打包工具,通过合理配置和优化,可以构建出高效、可维护的前端应用。