0%

优雅的使用cdn

cdn 网站的选择

  • 我习惯使用 unpkg, 因为其跟 npm 绑定, 软件包发布到 npm 上, 就可以使用该cdn

使用方式, 使用 moment 作为例子

  1. npm 网站中搜索 moment
  2. 点开 code 标签
  3. 观察目录结构, 直接目录下没有 min.js 结尾文件, 但是有个 min 目录
  4. 点开 min 目录, 发现 locales.min.js moment-with-locales.min.js moment.min.js
  5. 根据项目了解, 这三个文件分别对应 moment 本地化, moment 本体 + moment 本地化, moment 本体(不含本地化)
  6. 依据习惯, 使用 moment-with-locales.min.js
  7. 手动拼接目录: https://unpkg.com/moment/min/moment-with-locales.min.js 并点击访问
  8. 目录访问成功, 证明路径没有问题
  9. 将路径组装为 js 标签: <script src="https://unpkg.com/moment/min/moment-with-locales.min.js" />
  10. 将 js 标签放到 h5 中
  11. 在 h5 js 代码中使用: console.log(moment)

例外情况

  1. 大部分情况下, 使用 cdn 导入的包会生成一个与包名相同的变量, 如 moment 包, 会生成 moment 变量, 直接在 h5 代码中调用即可
  2. 然而少部分包, 由于使用量大, 其生成的变量名与包名不同, 而是使用一些符号, 例子如下:
    1. lodash => _
    2. jquery => $

如何寻找全局变量名, 以 lodash 为例

查看源码

  1. 浏览器中搜索: unpkg lodash, 点击进入网页版

    或者直接拼接链接进入网页版: https://unpkg.com/browse/lodash@4.17.21/
    最后一个 / 不能省略

  2. 依据经验, 搜索 lodash.js, 点开查看源码如下

也可能叫其他的, 如 index.js, lodash.mjs 等
也可以直接查看 lodash.min.js , 因为代码压缩过, 可读性不好, 需要复制下来通过编辑器格式化后查看
不想下载也可以试试通过浏览器的请求预览, 看是否能够格式化代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
;(function() {
// ...

/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;

/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;

/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
// ...
// Export lodash.
var _ = runInContext();

// Some AMD build optimizers, like r.js, check for condition patterns like:
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
// Expose Lodash on the global object to prevent errors when Lodash is
// loaded by a script tag in the presence of an AMD loader.
// See http://requirejs.org/docs/errors.html#mismatch for more details.
// Use `_.noConflict` to remove Lodash from the global object.
root._ = _;

// Define as an anonymous module so, through path mapping, it can be
// referenced as the "underscore" module.
define(function() {
return _;
});
}
// Check for `exports` after `define` in case a build optimizer adds it.
else if (freeModule) {
// Export for Node.js.
(freeModule.exports = _)._ = _;
// Export for CommonJS support.
freeExports._ = _;
}
else {
// Export to the global object.
root._ = _;
}
}.call(this));
  1. 省略的都是定义方法的代码, 不会实际执行
  2. 依据经验, global, self 等全局变量是 import 之前时代的 打包约定, 这里忽略即可
  3. 所以 root 变量即为 this, 所以在 h5 中直接使用 _ 即可获得 lodash 对象, 并调用 debounce 等方法