5

Vue + Webpack项目利用CDN加载静态文件,减少打包后的代码体积

 3 years ago
source link: https://blog.star7th.com/2019/03/2340.html
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.

Vue + Webpack项目利用CDN加载静态文件,减少打包后的代码体积

在使用Vue前端项目,比如说配合Element-ui框架使用时,由于加载比较多的静态资源文件,打包出来的js往往比较大,超过1M也不奇怪。
在传统的前端项目里,对于一些公用的js问题,比如说vue.min.js等,我们可以通过cdn加载,而不需要在我们业务层去引用,从而减少要加载的业务代码体积,有利于减轻我们服务器的压力。那么问题来了,Vue项目使用webpack打包时候,我们如何像传统方式那样加载公共CDN的静态资源文件呢?

首先在开发目录的index.html里的head标签里增加(这里只是例子,不同项目不同版本的链接可能不一样):

<script src="//cdn.staticfile.org/vue/2.5.13/vue.min.js"></script>
<script src="//cdn.staticfile.org/element-ui/2.0.8/index.js"></script>
<link href="//cdn.staticfile.org/element-ui/2.0.8/theme-chalk/index.css" rel="stylesheet">

在build/webpack.base.conf.js的module.exports里增加属性:

externals: {
  'vue': 'Vue',
  'element-ui': 'ELEMENT'
}

然后在开发目录的main.js文件里这样引用:

import Vue from 'vue'
import ELEMENT from 'element-ui'
Vue.use(ELEMENT)

然后再重新回到命令行,执行npm run build ,是不是发现打包出来的js文件小很多了。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK