模块标准
CommonJS
CommonJS
有三个全局变量 module
、exports
和 require
。但是由于 AMD
也有 require
这个全局变量,故不使用这个变量来进行检测。
如果想要对外提供接口的话,可以将接口绑定到 exports
(即 module.exports
) 上。
function MyModule() { // ...}if(typeof module !== `undefined` && typeof exports === `object`) { module.exports = MyModule;}
CMD
CMD
规范中定义了 define
函数有一个公有属性 define.cmd
。
CMD
模块中有两种方式提供对外的接口,一种是 exports.MyModule = ...
,一种是使用 return
进行返回。
AMD
AMD
规范中,define
函数同样有一个公有属性 define.amd
。
AMD
中的参数便是这个模块的依赖。那么如何在 AMD
中提供接口呢?它是返回一个对象,这个对象就作为这个模块的接口,故我们可以这样写:
function MyModule() { // ...}if(typeof define === `function` && define.amd) { define(function() { return MyModule; });}
总结
我们除了提供 AMD
模块接口,CMD
模块接口,还得提供原生的 JS 接口。
CMD
和 AMD
都可以使用 return
来定义对外接口,故可以合并成一句代码。 一个直接可以用的代码如下:
;(function(){ function MyModule() { // ... } var moduleName = MyModule; if (typeof module !== 'undefined' && typeof exports === 'object') { module.exports = moduleName; } else if (typeof define === 'function' && (define.amd || define.cmd)) { define(function() { return moduleName; }); } else { this.moduleName = moduleName; }}).call(this || (typeof window !== 'undefined' ? window : global);