本文共 2387 字,大约阅读时间需要 7 分钟。
vuecli做了个spa项目,大概有几十个个路由
直接 npm run build打包出来,有一个 1M的巨大 js文件,导致首页白屏时间过长分析工具
vuecli 2.x自带了分析工具,只要运行 npm run build --report如果是 vuecli 3的话,先安装插件
cnpm intall webpack-bundle-analyzer -–save-dev
然后新建vue.config.js,对 webpack进行配置:
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') } } }
再运行 npm run build --report
会在浏览器打开一个项目打包的情况图,便于直观地比较各个 bundle文件的大小
1、路由懒加载
在 router.js文件中,原来的静态引用方式,如:import ShowBlogs from '@/components/ShowBlogs'routes:[ path: 'Blogs', name: 'ShowBlogs', component: ShowBlogs ]
改为:
routes:[
path: ‘Blogs’, name: ‘ShowBlogs’, component: () => import(’./components/ShowBlogs.vue’) ]
如果是在 vuecli 3中,我们还需要多做一步工作
因为 vuecli 3默认开启 prefetch(预先加载模块),提前获取用户未来可能会访问的内容 在首屏会把这十几个路由文件,都一口气下载了 所以我们要关闭这个功能,在 vue.config.js中设置:2、ui框架按需加载
这里以饿了么ui为例: 原本的引进方式引进了整个包:import ElementUI from 'element-ui'Vue.use(ElementUI)
但实际上我用到的组件只有按钮,分页,表格,输入与警告
所以我们要按需引用:import { Button, Input, Pagination, Table, TableColumn, MessageBox } from 'element-ui';Vue.use(Button)Vue.use(Input)Vue.use(Pagination)Vue.prototype.$alert = MessageBox.alert
注意 MessageBox注册方法的区别,并且我们虽然用到了 alert,但并不需要引入 Alert组件
在 .babelrc / babel.config.js文件中添加( vue-cli 3要先安装 babel-plugin-component):
plugins: [ [ "component", { "libraryName": "element-ui", "styleLibraryName": "theme-chalk" } ] ]
3、gzip压缩
安装 compression-webpack-plugincnpm i compression-webpack-plugin -D
在 vue.congig.js中引入并修改 webpack配置:
const CompressionPlugin = require('compression-webpack-plugin')configureWebpack: (config) => { if (process.env.NODE_ENV === 'production') { // 为生产环境修改配置... config.mode = 'production' return { plugins: [new CompressionPlugin({ test: /\.js$|\.html$|\.css/, //匹配文件名 threshold: 10240, //对超过10k的数据进行压缩 deleteOriginalAssets: false //是否删除原文件 })] } }
在服务器我们也要做相应的配置
如果发送请求的浏览器支持 gzip,就发送给它 gzip格式的文件 我的服务器是用 express框架搭建的 只要安装一下 compression就能使用const compression = require('compression')app.use(compression())`注意,后面这一句,要放在所有其他中间件注册之前``
转载地址:http://dilsn.baihongyu.com/