1.路由懒加载
{
path: "/",
name: "Home",
meta: {
title: "Home - 首页",
},
// component: () => import("@/views/Home/home.vue"), import 会在页面加载router时全部调用加载一次 require引入方式仅在用户进去页面时加载当前页面
component: (resolve) => require(["@/views/Home/home.vue"], resolve),
},
此方法会把原本打包到一个app.js文件分开成多个js文件打包,这样会减小单个文件的大小,但是不会减小整个js文件夹的大小。通过这种方式可以做到按需加载,只加载单个页面的js文件。
2.组件异步加载
加载首页的时候,可以先给首页的子组件设置v-if加载条件。通过computed判断是否加载子组件
<add-staff
@addSupplementaryData="addSupplementaryData"
v-if="isSupplementary">
</add-staff>
computed:{
isSupplementary() {
return this.$store.state.triggerSave;
},
}
3.打包优化
(1).安装
npm i -D compression-webpack-plugin
(2)新建vue.config.js并引入
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const isProduction = process.env.NODE_ENV !== 'development'
// webpack 打包优化处理
configureWebpack: config => {
// 代码压缩
if (isProduction) {
// config.optimization.minimizer[0].options.terserOptions.compress.drop_console = true
// Gzip压缩
const productionGzipExtensions = ['html', 'js', 'css']
config.plugins.push(
// eslint-disable-next-line no-undef
new CompressionWebpackPlugin({
filename: '[path].gz[query]', // 目标资源名称。 [file] 会被替换成原始资源。[path] 会被替换成原始资源的路径, [query] 会被替换成查询字符串。默认值是 "[path].gz[query]"
algorithm: 'gzip', // 可以是 function(buf, callback) 或者字符串。对于字符串来说依照 zlib 的算法(或者 zopfli 的算法)。默认值是 "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'
}
}
}
}
}
},
4.图片进项压缩处理
// 图片压缩设置
chainWebpack: config => {
// 图片打包压缩,使用了 --- image-webpack-loader --- 插件对图片进行压缩
config.module
.rule('images')
.use('image-webpack-loader')
.loader('image-webpack-loader')
.options({ bypassOnDebug: true })
.end()
},
一般进行上述处理可以很大程度的优化代码量,从而达到加快首屏加载速度的需求。
上述代码可能会有一些依赖需要安装,我就不一一介绍了。可以根据启动时的报错依次安装相应的依赖即可。希望能帮到大家。