CommonJS规范
服务器端规范,Node.js推广使用。该规范的核心是:允许模块使用require方法来同步加载所依赖的其他模块,然后通过exports或module.exports导出需要暴露的接口。
- 一个模块是一个文件
- 使用module.exports或exports导出模块
// module.js
exports.add = (a, b) => a+b
module.exports = {
add: (a, b) => a + b
}
- 使用require加载模块
- require命令第一次加载模块时,执行整个脚本,在内存中生成对象
- 多次执行require命令再次加载该模块时,不会再执行该脚本,直接从缓存中取值
- CommonJS加载模块是同步加载模块
- 不适合作为浏览器的规范,由于CommonJS是同步加模块,在服务端加载模块时都是从本地硬盘中加载,读取速度很快。但是在浏览器端加载模块时,需要请求服务器端,涉及网速、代理的问题,一旦等待时间过长,浏览器会处于“假死”状态。
ADM规范
AMD(Asynchronous Module Definition)异步模块定义,客户端规范。采用异步方式加载模块,模块加载不影响它后面语句的代执行。AMD是require.js在推广使用过程中对模块定义规范化的产物。在使用时,需引入require.js。
- 使用define()定义模块
/**
+ @param id 模块名称,如果为空,模块的名字默认为模块加载器请求的指定脚本名
+ @param dependencies 模块依赖
+ @param factory 工场函数,模块初始化执行的函数或对象
*/
define(id? dependencies? factory)
- 使用require加载模块,AMD是依赖前置模块
require([module], callback)
CMD规范
CMD(Common Module Definition)通用模块定义,异步加载模块。CMD是sea.js在推广过程中对模块定义的规范化产物。在使用时,需引入sea.js。
- 使用define()定义模块,使用require()加载模块,CMD模块加载是推崇就近依赖的,需要到某个模块时再进行require加载
define(function (require, exports, module) {
let a = require('a')
let b = require('b')
exports.eat = a.eat
exports.run = b.run
})
- 使用seajs.use加载使用模块
seajs.use(id, callback?)
UMD规范
UMD(Universal Module Definition)通用模块定义,为了兼容AMD、CMD和无模块化开发规范.
/**
+ UMD-Universal Module Definition 通用模块定义
+ */
(function (root, factory) {
// 判断是否是AMD/CMD
if (typeof define === 'function') {
define([], factory)
} else if (typeof exports === 'object') {
// Node CommonJS规范
module.exports = factory()
} else {
// 浏览器环境
root.someAttr = factory
}
})(this, function () {
let add = function (a, b) {
return a + b
}
return {
add,
module: 'UMD'
}
})
ES6模块
ES6通过imort和export实现模块的输入与输出,import命令用于输入其他模块提供的功能,export命令用于规定模块对外的接口。
- 使用export导出模块
// test.js
export let module = 'ES6 Module'
export let hello = function () {}
let demo = function () {}
// 默认导出
export default demo
- 使用import导入模块
// 导入默认模块
import demo from './test.js'
// 导入指定模块
import { hello, module } from './test'
// 导入指定模块,并重命名
import { hello as hi, module } from './test.js'
// 导入全部模块,并重命名
import * as test from './test.js'
本文由 前端技术精髓 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: Apr 2, 2020 at 09:48 am