vue引入element-ui之后生成的vendor特别大,导致第一次访问页面加载特别慢,查询了网上的一些方法,大致有几个方式可以解决
- cdn
- gzip
- vue路由懒加载
- element-ui按需引入
cdn
使用cdn的方式在index.html中引用,不过我试了,不知道是不是没有弄对,按照网上的操作了之后,打的包是小了,但是element-ui没有引入进去,好像是因为我只引入了element-ui的cdn,vue还是使用的打包的方式,我觉得Vue还是用打包的方式引入好一点,加上这种方式我认为扩展和安全性不能保证,自己去备案网站弄cdn又太麻烦,遂弃之。
gzip
使用Gzip,这种方式需要后端服务器支持,可以在打包的时候生成.gz文件,需要一点配置,首先安装插件
npm i install compression-webpack-plugin -D
然后在vue.config.js
里面加上内容
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i;
const CompressionWebpackPlugin = require('compression-webpack-plugin');
//----module.exports中的内容------
configureWebpack: config => {
if (process.env.NODE_ENV === 'production') {
return {
plugins: [
new CompressionWebpackPlugin({
filename: '[path].gz[query]',
algorithm: 'gzip',
test: productionGzipExtensions,
threshold: 2048,
minRatio: 0.8
})
]
}
}
},
这个时候执行npm run build
就会发现dist对应类型下多了.gz
文件
然后在nginx中映射静态文件的位置加上gzip_static on
location / {
try_files $uri $uri/ /index.html;
root html/;
index index.html index.htm;
gzip_static on;
}
此时打开浏览器,会发现第一次访问的时候,拉下来的包是压缩过后的大小,而且响应的请求头多了一项Content-Encoding: gzip
,加载速度明显快得多
vue路由懒加载
这个可以参考Vue官方的文档,写得还是很详细:传送门
大致就是把引入改为动态的引入
import Frame from './page/Frame'
const routes = [{
path: '/talk-frame',
name: 'Frame',
component: Frame
}]
变为
const routes = [{
path: '/talk-frame',
name: 'Frame',
component: () => import( /* webpackChunkName: "base" */'./page/Frame')
}]
element-ui按需引入
可以参考element-ui官方的介绍:传送门
但是我觉得这个很麻烦,所以没有去弄>_>
写在最后
最终我还是只用了Gzip和路由懒加载的方式,因为我的页面很简单,也是自己的一个练手的项目,使用Gzip之后速度已经很快了(使用之前7s,现在2s),
自己也是一个刚入前端门(或许还没入门)后台猿,对于前段工程化和优化的方式还不了解,最近也是才学了es6和vue,所以如果有什么写得不对的地方,欢迎批评指正,另外有什么其他的优化方式也请不吝赐教
在查找的过程中也找到一个webpack打包分析工具,
npm install --save-dev webpack-bundle-analyzer
安装之后配置一下vue.config.js
(见附录)
执行npm run build --report
就会自动打开一个网页
使用可以参考这里: www.npmjs.com/package/web…
附录
完整配置
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i;
const CompressionWebpackPlugin = require('compression-webpack-plugin');
module.exports = {
// 生产环境不生成sourceMap文件
productionSourceMap:false,
// runtimeCompiler: true
configureWebpack: config => {
// 执行npm run build的时候会把NODE_ENV改为production
if (process.env.NODE_ENV === 'production') {
return {
plugins: [
new CompressionWebpackPlugin({
filename: '[path].gz[query]',
algorithm: 'gzip',
test: productionGzipExtensions,
threshold: 2048,
minRatio: 0.8
})
]
}
}
},
//webpack-bundle-analyzer配置
chainWebpack: (config) => {
if (process.env.NODE_ENV === 'production') {
if (process.env.npm_config_report) {
config.plugin('webpack-bundle-analyzer')
.use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
.end();
config.plugins.delete('prefetch')
}
}
}
}
参考
- Gzip:blog.csdn.net/choujiaobm0…
- cdn方式引入: www.pianshen.com/article/966…
- 首屏优化: mp.weixin.qq.com/s/O4EVlKnYK…