Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vue-cli 项目中引用 CDN 上的 JS/CSS 库 #42

Closed
Dream4ever opened this issue Jun 11, 2018 · 0 comments
Closed

vue-cli 项目中引用 CDN 上的 JS/CSS 库 #42

Dream4ever opened this issue Jun 11, 2018 · 0 comments
Labels
Front-end Everything you see and experience JS Javascript

Comments

@Dream4ever
Copy link
Owner

Dream4ever commented Jun 11, 2018

需求描述

目前在 vue-cli 中引入库的方式,是通过 npm 安装,然后 webpack 打包。用起来的确很方便,但是这样一来,打包后的文件体积就会变得很大,vendor.js 的体积普遍在几百 K 上下,而这几百 K 完全可以通过公共 CDN 来分流,毕竟服务器的带宽是有限的。

方案调研

调研过程

vue-cli use cdn 作为关键字搜索,网上给出的建议 How to include a CDN to VueJS CLI without NPM or Webpack?vue项目优化--使用CDN和Gzip,说是可以在 index.html 中静态引入,或者在具体的组件中用 JS 动态引入。这两种方式引入的库都全局可用,自己做的页面都是小项目,不用担心全局变量污染的情况,那就试试吧。

入选方案

应用过程

  • 先用 yarn 把安装好的 vue 删除:yarn remove vue
  • 然后在 index.html 中添加 Vue 的 CDN 链接,这里用的是 bootcdn 提供的服务。
  • 如果启用了 ESLint,会提示没有定义 Vue,就需要编辑 .eslintrc.js,加上 'globals': { 'Vue': false } 这项设置,注意,如果开发环境已启动,需要重启开发环境,这项设置才能生效。
  • 告诉 webpack 不要打包 Vue:编辑 build\webpack.base.conf.js,最后加上 externals: { vue: 'Vue', } 这项设置,属性值 Vue 是模块暴露出来的全局名称。
  • 最后再把 main.js 中对 Vue 的引用删除:import Vue from 'vue' 这句如果不删除,开发环境是一直会报错的。

要点总结

最开始想的是把普通的库通过 CDN 的方式引入,不过最后直接来了个大的,把 Vue 也从外部引入了,测试了一下编译后的 js 文件,体积果然小了很多,赞!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Front-end Everything you see and experience JS Javascript
Projects
None yet
Development

No branches or pull requests

1 participant