随着 Web 前端技术的不断发展,Vue.js 已经成为了一款非常受欢迎的前端框架。Vue.js 中的 Vue-cli 和 Webpack 作为构建工具也成为了必要的配套工具。在开发项目时,我们通常会使用 Vue-cli 来搭建应用程序框架,使用 Webpack 打包发布项目。但是在大项目打包发布过程中,由于项目体积庞大,可能会出现编译速度慢、打包体积大、访问速度较慢等问题,为了避免这些问题的出现,本篇文章将介绍 Vue-cli 和 Webpack 打包发布优化指南,帮助开发者更好地优化大型项目的发布效果。
一、Vue-cli 项目优化
- 按需引入第三方组件
在开发过程中,我们通常会使用 jQuery、Bootstrap、Echarts 等第三方库,但是引入整个库可能会造成打包体积过大,访问速度慢的问题。因此,我们可以使用 babel-plugin-component
插件来进行按需引入。
在 babel.config.js
中设置:
plugins: [
['component', {
libraryName: 'element-ui',
styleLibraryName: 'theme-chalk'
}]
]
这里以 Element-ui
为例,使用插件按需引入库,可以大大减少打包体积。
- 配置 Webpack 属性
我们可以通过修改 vue.config.js
文件来修改 Webpack 的配置属性。以下是一些常用的 Webpack 属性的配置方法:
// 修改输出文件名格式
output: {
filename: '[name].[hash].js'
}
// 修改 publicPath
publicPath: process.env.NODE_ENV === 'production' ?
'/production-sub-path/' : '/'
// 压缩代码
uglifyOptions: {
compress: {
warnings: false,
drop_console: true,
drop_debugger: true,
dead_code: true
}
}
// 配置 externals,将大型的第三方库从打包代码中剥离
externals: {
'vue': 'Vue',
'jquery': 'jQuery',
'bootstrap': 'Bootstrap',
'echarts': 'echarts',
'moment': 'moment'
}
// 使用 Webpack-bundle-analyzer 查看打包后的各个模块的大小
configureWebpack: {
plugins: [
new BundleAnalyzerPlugin()
]
}
二、Webpack 优化
- 使用多线程构建
使用多线程构建可以大大提高打包速度,可以使用 happypack
插件来实现多线程构建。使用该插件需要先安装 happypack
:
npm install happypack -D
接下来将原来的配置文件:
module: {
rules: [
{
test: /.js$/,
loader: 'babel-loader'
},
...
]
}
修改为:
const HappyPack = require('happypack');
const happyThreadPool = HappyPack.ThreadPool({ size: os.cpus().length });
module: {
rules: [
{
test: /.js$/,
exclude: /node_modules/,
loader: 'happypack/loader?id=happyBabel'
},
...
]
},
plugins: [
new HappyPack({
id: 'happyBabel',
loaders: ['babel-loader'],
threadPool: happyThreadPool,
verbose: true
})
]
这里使用 happypack
插件来启用多线程构建。
- 使用 DllPlugin 和 DllReferencePlugin 技术
DllPlugin 和 DllReferencePlugin 技术主要是将一些不经常变动的库单独打包成一个 lib 文件,这样在每次打包时就不用再去打包这些库文件,只需要在之后使用 DllReferencePlugin 进行引入即可。
使用方法:
- 先配置 DllPlugin:
const path = require('path');
const webpack = require('webpack');
const dllPath = 'static/dll';
module.exports = {
entry: {
vendor: ['vue', 'vue-router', 'vuex', 'axios', 'lodash'] // 需要单独打包的库
},
output: {
path: path.join(__dirname, `../${dllPath}`),
filename: '[name].dll.js',
library: '[name]_[hash]' // 暴露全局变量,避免前后两次打包,库名字变更
},
plugins: [
new webpack.DllPlugin({
name: '[name]_[hash]',
path: path.join(__dirname, `../${dllPath}`, 'manifest.json')
})
]
};
- 执行打包:
cross-env NODE_ENV=production webpack --config ./build/webpack.dll.js --progress --hide-modules
- 在
index.html
中使用 <script>
引入生成的库文件:
<script src="<%= BASE_URL %>static/dll/vendor.dll.js"></script>
- 配置 DllReferencePlugin:
const AddAssetHtmlWe
.........................................................