2

给 Vue 项目中的 vendor.js 文件瘦身

 2 years ago
source link: https://hooray.github.io/posts/c25b8237/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

在 Vue 项目开发中,会引用各种第三方库来提高开发效率,这就导致打包后的 vendor.js 文件体积相当臃肿,在加载时页面空白时间过长,用户体验很差。

要解决这个问题也很简单,既然是第三方的库,那其实就没必要都放在项目里,可以通过 CDN 的方式引入,不仅能减小 vendor.js 的体积,在加载速度上,也会用提升。

那在 Vue 项目中,要如何实现通过 CDN 引入第三方库并正常使用呢,下面就跟着我一步步来操作吧。

修改 index.html

找到 public/index.html 文件,将需要引入第三方库的 CDN 地址放进来。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title>vue-automation</title>
</head>
<body>
<noscript>
<strong>We're sorry but vue-automation doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script>
<script src="https://cdn.bootcss.com/vue-router/3.1.3/vue-router.min.js"></script>
<script src="https://cdn.bootcss.com/vuex/3.1.1/vuex.min.js"></script>
<script src="https://cdn.bootcss.com/axios/0.19.0/axios.min.js"></script>
<script src="https://cdn.bootcss.com/qs/6.8.0/qs.min.js"></script>
<script src="https://cdn.bootcss.com/lodash.js/4.17.15/lodash.min.js"></script>
<script src="https://cdn.bootcss.com/moment.js/2.24.0/moment.min.js"></script>
</body>
</html>

修改 vue.config.js

这里的修改其实是配置 webpack 的外部扩展(externals

module.exports = {
...
configureWebpack: {
externals: {
'vue': 'Vue',
'vue-router': 'VueRouter',
'vuex': 'Vuex',
'axios': 'axios',
'qs': 'Qs',
'lodash': '_',
'moment': 'moment'
}
}
...
}

externals 中,key 是 require 的包名,value 是全局的变量

修改 main.js

这一步就是要修改代码中的引入方式了,需要把原先用 import 引入的,改为 require 方式引入,就像这样。

// import Vue from 'vue'
const Vue = require('vue')

// import axios from 'axios'
const axios = require('axios')
// import qs from 'qs'
const qs = require('qs')

// import lodash from 'lodash'
const lodash = require('lodash')
Vue.prototype._ = lodash

// import moment from 'moment'
const moment = require('moment')
Vue.prototype.$moment = moment

当然不局限在 main.js 里,其它文件里如果有用到这些第三方库的地方,也需要一并修改掉。

修改完上面这三处地方后,我们可以打包看看实际效果变化有多大。

优化前

优化后

可以看到,优化前后的效果还是很明显的,从原先接近 500kb 的大小,一下减到 58kb 了,体积压缩到只有原先的八分之一。

当然,这只是 Vue 项目打包优化中的冰山一角,还有很多优化技巧,比如大家比较熟知的路由懒加载,这里就不展开了。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK