Vue3 Webpack 完整配置指南
1. 基础配置结构
const path = require('path');
const { VueLoaderPlugin } = require('vue-loader');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
// 入口配置
entry: './src/main.js',
// 输出配置
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/[name].[contenthash].js',
publicPath: '/',
clean: true
},
// 模块解析配置
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'@': path.resolve(__dirname, 'src'),
'vue$': 'vue/dist/vue.runtime.esm-bundler.js'
}
},
// 模块规则配置
module: {
rules: []
},
// 插件配置
plugins: [],
// 开发服务器配置
devServer: {}
}
2. 详细配置说明
2.1 入口(entry)配置
entry: {
app: './src/main.js',
// 多入口配置
admin: './src/admin.js'
}
说明:
- 定义webpack打包的入口文件
- 可以配置单入口或多入口
- 支持动态导入实现代码分割
2.2 输出(output)配置
output: {
// 输出目录
path: path.resolve(__dirname, 'dist'),
// 输出文件名
filename: 'js/[name].[contenthash].js',
// chunk文件名
chunkFilename: 'js/[name].[chunkhash].js',
// 资源文件名
assetModuleFilename: 'assets/[hash][ext][query]',
// 公共路径
publicPath: '/',
// 清理dist目录
clean: true
}
2.3 模块(module)配置
module: {
rules: [
// Vue文件加载器
{
test: /\.vue$/,
loader: 'vue-loader'
},
// JavaScript转译
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
plugins: ['@babel/plugin-transform-runtime']
}
}
},
// CSS处理
{
test: /\.(css|scss)$/,
use: [
process.env.NODE_ENV === 'production'
? MiniCssExtractPlugin.loader
: 'vue-style-loader',
'css-loader',
'postcss-loader',
'sass-loader'
]
},
// 图片处理
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset',
parser: {
dataUrlCondition: {
maxSize: 8 * 1024 // 8kb
}
}
}
]
}
2.4 插件配置及说明
plugins: [
// Vue Loader插件
new VueLoaderPlugin(),
// HTML生成插件
new HtmlWebpackPlugin({
template: './public/index.html',
filename: 'index.html',
title: 'Vue3 App'
}),
// 清理插件
new CleanWebpackPlugin(),
// CSS提取插件
new MiniCssExtractPlugin({
filename: 'css/[name].[contenthash].css'
}),
// 定义环境变量
new webpack.DefinePlugin({
__VUE_OPTIONS_API__: true,
__VUE_PROD_DEVTOOLS__: false
}),
// 复制静态资源
new CopyWebpackPlugin({
patterns: [
{
from: path.resolve(__dirname, 'public'),
to: path.resolve(__dirname, 'dist'),
globOptions: {
ignore: ['**/index.html']
}
}
]
})
]
2.5 开发服务器配置
devServer: {
static: {
directory: path.join(__dirname, 'public')
},
compress: true,
port: 8080,
hot: true,
open: true,
historyApiFallback: true,
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
pathRewrite: { '^/api': '' }
}
}
}
3. 常用插件详解
3.1 核心插件
- VueLoaderPlugin
- 功能:处理Vue单文件组件
- 安装:
npm install vue-loader
- HtmlWebpackPlugin
- 功能:生成HTML文件并自动注入打包后的资源
- 安装:
npm install html-webpack-plugin
- MiniCssExtractPlugin
- 功能:将CSS提取到单独文件
- 安装:
npm install mini-css-extract-plugin
3.2 优化插件
- TerserWebpackPlugin
optimization: {
minimize: true,
minimizer: [
new TerserWebpackPlugin({
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true
}
}
})
]
}
- 功能:压缩JavaScript代码
- 安装:
npm install terser-webpack-plugin
- CssMinimizerWebpackPlugin
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
optimization: {
minimizer: [
new CssMinimizerPlugin()
]
}
- 功能:压缩CSS代码
- 安装:
npm install css-minimizer-webpack-plugin
- CompressionWebpackPlugin
new CompressionWebpackPlugin({
algorithm: 'gzip',
test: /\.(js|css|html|svg)$/,
threshold: 10240,
minRatio: 0.8
})
- 功能:生成gzip压缩文件
- 安装:
npm install compression-webpack-plugin
3.3 分析插件
- BundleAnalyzerPlugin
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
plugins: [
new BundleAnalyzerPlugin()
]
- 功能:分析打包结果
- 安装:
npm install webpack-bundle-analyzer
4. 优化配置示例
4.1 分割代码
optimization: {
splitChunks: {
chunks: 'all',
minSize: 20000,
minRemainingSize: 0,
minChunks: 1,
maxAsyncRequests: 30,
maxInitialRequests: 30,
enforceSizeThreshold: 50000,
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10,
reuseExistingChunk: true
},
common: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
}
}
4.2 缓存配置
module.exports = {
cache: {
type: 'filesystem',
buildDependencies: {
config: [__filename]
}
}
}
5. 完整生产环境配置示例
const path = require('path');
const { VueLoaderPlugin } = require('vue-loader');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
mode: 'production',
entry: './src/main.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/[name].[contenthash].js',
chunkFilename: 'js/[name].[chunkhash].js',
publicPath: '/',
clean: true
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'@': path.resolve(__dirname, 'src'),
'vue$': 'vue/dist/vue.runtime.esm-bundler.js'
}
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
plugins: ['@babel/plugin-transform-runtime']
}
}
},
{
test: /\.(css|scss)$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader'
]
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset',
parser: {
dataUrlCondition: {
maxSize: 8 * 1024
}
}
}
]
},
plugins: [
new CleanWebpackPlugin(),
new VueLoaderPlugin(),
new HtmlWebpackPlugin({
template: './public/index.html',
filename: 'index.html',
minify: {
removeComments: true,
collapseWhitespace: true
}
}),
new MiniCssExtractPlugin({
filename: 'css/[name].[contenthash].css'
}),
new CompressionPlugin({
algorithm: 'gzip',
test: /\.(js|css|html|svg)$/,
threshold: 10240,
minRatio: 0.8
})
],
optimization: {
minimizer: [
new TerserPlugin({
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true
}
}
}),
new CssMinimizerPlugin()
],
splitChunks: {
chunks: 'all',
cacheGroups: {
vendors: {
name: 'chunk-vendors',
test: /[\\/]node_modules[\\/]/,
priority: -10,
chunks: 'initial'
},
common: {
name: 'chunk-common',
minChunks: 2,
priority: -20,
chunks: 'initial',
reuseExistingChunk: true
}
}
}
},
performance: {
hints: false
}
}
这是一个完整的Vue3 Webpack配置指南,我主要从以下几个方面进行了详细说明:
- 基础配置结构
- 各配置项的详细说明
- 常用插件介绍及配置方法
- 优化相关配置
- 完整的生产环境配置示例
每个部分都包含了详细的代码示例和说明。你可能特别需要注意以下几点:
- 开发环境和生产环境的区分配置
- 性能优化相关的插件使用
- 缓存策略的配置
- 代码分割的实现
评论区