系列文章目录
第一章 vue3前端架构—打包配置
前言
vue.config.js 是一个可选的配置文件,如果项目的根目录中存在这个文件,那么它会被 @vue/cli-service 自动加载。
一、vue.config.js常用的配置项

二、常用配置项的使用
常用的配置项如上表所示,在实际项目开发中,涉及到的使用点结合代码简单进行介绍,可以进行性能优化,还有其他方式可以进一步的优化处理,本文简单就配置中的几点进行说明:
const { defineConfig } = require('@vue/cli-service')
const CompressionWebpackPlugin = require("compression-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const path = require('path')
// 是否为生产环境
const isProduction = process.env.NODE_ENV !== 'development'
const resolve = dir => {
return path.join(__dirname, dir)
}
// 打包性能监视
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");
// 开启多线程打包
const HappyPack = require('happypack')
const os = require('os')
const happyThreadPool = HappyPack.ThreadPool({ size: os.cpus().length });
module.exports = defineConfig({
publicPath: './', // 所有的资源都会被链接为相对路径,这样打出来的包可以被部署在任意路径(之前是baseUrl,3.3之后更换了)
outputDir: 'dist', // 输出文件目录
assetsDir: 'static', // 放置静态文件
lintOnSave: true, // 保存的时候做lint检查
transpileDependencies: true,
productionSourceMap: false, // 生产环境关闭sourcemap
filenameHashing: true, //生成的静态资源在它们的文件名中包含了 hash 以便更好的控制缓存,默认值为true
devServer: {
open: true, // 配置自动启动浏览器
port: 8888, // 设置本地访问端口号
proxy: {
'/api': {
target: 'http://localhost:5555', // 转发 API 请求到本地的 Node.js 服务器
changeOrigin: true,
pathRewrite: {
'^/api': '' // 去除 URL 中的 /api 部分
}
}
}
},
chainWebpack: config => {
config.resolve.alias
.set('@', resolve('src')) // 配置别名
config.module // 开启图片压缩,将大的图片进行压缩从而缩小打包体积
.rule('images')
.use('image-webpack-loader')
.loader('image-webpack-loader')
.options({ bypassOnDebug: true })
.end()
},
configureWebpack: config => {
if(isProduction) {
// gzip压缩
const productionGzipExtensions = ['html', 'js', 'css']
config.plugins.push(
new CompressionWebpackPlugin({
filename: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
'\.(' + productionGzipExtensions.join('|') + ')$'
),
threshold: 10240, // 只有大小大于该值的资源会被处理 10240
minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
deleteOriginalAssets: false // 删除原文件
})
)
// 公共代码抽离
config.optimization = {
splitChunks: {
cacheGroups: {
vendor: { // 外部插件
chunks: 'all',
test: /node_modules/,
name: 'vendor',
minChunks: 1,
maxInitialRequests: 5,
minSize: 0,
priority: 100
},
common: { // 业务公共代码
chunks: 'all',
test: /[\/]src[\/]js[\/]/,
name: 'common',
minChunks: 2,
maxInitialRequests: 5,
minSize: 0,
priority: 60
},
styles: { // 样式
name: 'styles',
test: /.(sa|sc|c)ss$/,
chunks: 'all',
enforce: true
},
runtimeChunk: {
name: 'manifest'
}
}
}
}
// 打包环境去掉console.log
config.optimization = {
minimizer: [
new TerserPlugin({
terserOptions: {
compress: {
drop_console: true, // 移除console.log
drop_debugger: false,
},
},
}),
],
}
}
//开启打包计时
config.plugins.push(new SpeedMeasurePlugin())
config.plugins.push(new HappyPack({
id:'babel',
loaders:['babel-loader?cacheDirectory=true'],
threadPool:happyThreadPool
})
)
}
})
1、productionSourceMap
在生产环境中,建议关闭sourcemap,可以提升打包速度。
2、image-webpack-loader
开启图片压缩,将大的图片进行压缩从而缩小打包体积,减少打包体积
chainWebpack: config => {
config.module // 开启图片压缩,将大的图片进行压缩从而缩小打包体积
.rule('images')
.use('image-webpack-loader')
.loader('image-webpack-loader')
.options({ bypassOnDebug: true })
.end()
}
3、开启gzip压缩
gizp压缩是一种http请求优化方式,通过减少文件体积来提高加载速度。html、js、css文件甚至json数据都可以用它压缩,可以减小60%以上的体积。
下面展示一些
const CompressionWebpackPlugin = require("compression-webpack-plugin");
config.plugins.push(
new CompressionWebpackPlugin({
filename: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
'\.(' + productionGzipExtensions.join('|') + ')$'
),
threshold: 10240, // 只有大小大于该值的资源会被处理 10240
minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
deleteOriginalAssets: false // 删除原文件
})
)
实测打包效果:

在nginx服务上增加以下配置:
gzip on; gzip_min_length 1k; gzip_buffers 4 16k; gzip_comp_level 5; gzip_types text/plain application/javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/png image/gif;
4、公共代码抽离
SplitChunks插件简单的来说就是Webpack中一个提取或分离代码的插件,主要作用是提取公共代码,防止代码被重复打包,拆分过大的js文件,合并零散的js文件。
splitChunks: {
cacheGroups: {
vendor: { // 外部插件
chunks: 'all',
test: /node_modules/,
name: 'vendor',
minChunks: 1,
maxInitialRequests: 5,
minSize: 0,
priority: 100
},
common: { // 业务公共代码
chunks: 'all',
test: /[\/]src[\/]js[\/]/,
name: 'common',
minChunks: 2,
maxInitialRequests: 5,
minSize: 0,
priority: 60
},
styles: { // 样式
name: 'styles',
test: /.(sa|sc|c)ss$/,
chunks: 'all',
enforce: true
},
runtimeChunk: {
name: 'manifest'
}
}
}
5、开启多线程打包
原理: 由于有大量文件需要解析和处理,构建是文件读写和计算密集型的操作,特别是当文件数量变多后,Webpack 构建慢的问题会显得严重。文件读写和计算操作是无法避免的,那能不能让 Webpack 同一时刻处理多个任务,发挥多核 CPU 电脑的威力,以提升构建速度呢?
HappyPack 就能让 Webpack 做到这点,它把任务分解给多个子进程去并发的执行,子进程处理完后再把结果发送给主进程。
const HappyPack = require('happypack')
config.plugins.push(new HappyPack({
id:'babel',
loaders:['babel-loader?cacheDirectory=true'],
threadPool:happyThreadPool
})
)
6、开启打包计时
speed-measure-webpack-plugin是一款统计 webpack 打包时间的插件,不仅可以分析总的打包时间,还能分析各阶段loader 的耗时,并且可以输出一个文件用于永久化存储数据
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");
//开启打包计时
config.plugins.push(new SpeedMeasurePlugin())

总结
以上就是今天要讲的内容,本文仅仅简单介绍了打包配置常见的使用,还有其他优化配置,比如开启CDN,打包文件大小分析等。