原因:由于前端静态资源包过大,会导致初始加载非常缓慢,因此需要优化,缩短时间。
一、优化前
1-1、开发时的网络请求
1-2、其打包过后的dist文件包
可以看出,即使是npm run build后,依旧很大,分别为大约2M、4M ,nginx后初始化加载时间为5秒多
下图可视化分析中可看清晰看出:
【在vue.config.js文件夹下配置可视化分析,可查看静态资源包分配及大小(优化步骤中会介绍如何配置)】
所以后面将进行gzip压缩优化
二、优化步骤+优化后
百度上有好几种优化方式,我尝试了splitchunks拆分优化+gzip压缩优化,下面将进行操作描述(不过感觉自己进行的splitchunks拆包优化的方式写的有些问题,所以导致使用了splitchunks拆分几乎没有起到什么作用)
首先要安装两个插件
2-1、先安装个webpack-bundle-analyzer插件,可以可视化分析打包后的文件(如一、优化前中介绍的可视化分析图)。
npm install webpack-bundle-analyzer --save-dev
在vue.config.js文件中进行配置【仅书写此步骤中主要的配置】
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports={
configureWebpack:config =>{
return {
plugins:[
new BundleAnalyzerPlugin()
]
}
}
}
npm run build 打包成功后,会自动弹出页面 http://127.0.0.1:8888
2-2、配置gzip压缩:安装compression-webpack-plugin插件
前端将文件打包成.gz文件,然后通过nginx的配置,让浏览器直接解析.gz文件,可以大大提升文件加载的速度。
npm install --save-dev compression-webpack-plugin
在vue.config.js文件中进行配置【仅书写此步骤中主要的配置】
const webpack = require('webpack');
const CompressionWebpackPlugin = require('compression-webpack-plugin');
const productionGzipExtensions = ['js', 'css'];
const isProduction = process.env.NODE_ENV === 'production';
module.exports = {
configureWebpack: {
plugins: [
// new BundleAnalyzerPlugin(),
// Ignore all locale files of moment.js
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
// 配置compression-webpack-plugin压缩
new CompressionWebpackPlugin({
algorithm: 'gzip',
test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
threshold: 10240,
minRatio: 0.8
}),
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 5,
minChunkSize: 100
})
],
}
}
如报下图错误:Cannot read property ‘tapPromise‘ of undefined
这是由于compression-compression-webpack-plugin插件的版本过高,可以修改版本号为6.1.1即可。
npm run build 打包后可查看dist文件夹为(一、优化前中有配置前的样子)
可以看出压缩优化后明显提升了一大截
2-3、进行splitchunks拆包优化【此步骤感觉我设置的有些问题,导致没起到什么优化的作用,只是拆分出了部分而已】【此步骤可不看】
直接放上我整个vue.config.js文件吧 关于splitchunks主要看里面的optimization内容即可
const Timestamp = new Date().getTime();
const path = require('path');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
// const path = require('path');
const webpack = require('webpack');
const CompressionWebpackPlugin = require('compression-webpack-plugin');
const productionGzipExtensions = ['js', 'css'];
const isProduction = process.env.NODE_ENV === 'production';
module.exports = {
configureWebpack: {
resolve: {
alias: {
vue$: 'vue/dist/vue.esm.js',
'@': path.resolve('src'),
'*': path.resolve('public'),
scss_vars: '@/assets/css/vars.scss'
}
},
plugins: [
new BundleAnalyzerPlugin(),
// Ignore all locale files of moment.js
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
// 配置compression-webpack-plugin压缩
new CompressionWebpackPlugin({
algorithm: 'gzip',
test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
threshold: 10240,
minRatio: 0.8
}),
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 5,
minChunkSize: 100
})
],
/* chainWebpack: config => {
config.plugin('webpack-bundle-analyzer').use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin);
}, */
output: {
// 输出重构 打包编译后的 文件名称 【模块名称.时间戳】
filename: `[name].${Timestamp}.js`,
chunkFilename: `[name].${Timestamp}.js`
},
optimization: {
splitChunks: {
chunks: 'all',
minSize: 1,
maxSize: 0,
minChunks: 1,
maxAsyncRequests: 8,
maxInitialRequests: 4,
// automaticNameDelimiter: '~',
cacheGroups: {
libs: {
name: 'chunk-libs',
test: /[\\/]node_modules[\\/]/,
priority: 10,
reuseExistingChunk: true,
chunks: 'initial' // only package third parties that are initially dependent
},
elementUI: {
name: 'chunk-elementUI', // split elementUI into a single package
priority: 19, // the weight needs to be larger than libs and app or it will be packaged into libs or app
reuseExistingChunk: true,
test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
},
echarts: {
name: 'chunk-echarts', // split elementUI into a single package
priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
reuseExistingChunk: true,
test: /[\\/]node_modules[\\/]_?echarts(.*)/ // in order to adapt to cnpm
},
brace: {
name: 'chunk-brace', // split elementUI into a single package
priority: 18, // the weight needs to be larger than libs and app or it will be packaged into libs or app
reuseExistingChunk: true,
test: /[\\/]node_modules[\\/]_?brace(.*)/ // in order to adapt to cnpm
},
commons: {
name: 'chunk-commons',
test: path.resolve('src/components'), // can customize your rules
minChunks: 3, // minimum common number
priority: 15,
reuseExistingChunk: true
}
}
}
}
},
/* */
// chainWebpack: config => {
// config
// .plugin('webpack-bundle-analyzer')
// .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
// },
publicPath: './',
assetsDir: './assets',
productionSourceMap: false,
filenameHashing: true,
lintOnSave: false,
devServer: {
proxy: {
'/edc-sys': {
target: '此处填写接口地址:域名端口号',
changeOrigin: true
},
'/edc': {
target: '此处填写接口地址:域名端口号',
// target: 'http://localhost:8030',
changeOrigin: true
}
}
},
pwa: {
iconPaths: {
// favicon32: './public/yun.png'
}
}
};
一堆东西,其实我没有看懂,并且拆分也只分离出来了部分内容(还没起到优化作用),src下的main.js怎么拆分出来啊,大神看到的话教教我吧,是需要靠cdn或者路由引入的方式吗,大写哭泣了!!!
npm run build后可查看到
dist文件
可视化分析
三、通过nginx查看到底有没有起作用
然后需要在nginx中设置
找到nginx文件夹,编辑conf/nginx.conf文件
在server{}中添加下列代码
server{
gzip on;
gzip_min_length 1k;
gzip_comp_level 9;
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
gzip_vary on;
gzip_disable "MSIE [1-6]\.";
}
然后再浏览器上输入http://127.0.0.1:17824/ 即可打开dist文件里的index.html页面 然后打开页面的控制台可查看到,加载时间大大的缩减了 从原先的5秒左右缩短到了现在的1秒左右