JavaScript如何让你的插件兼容AMD,CMD和原生JS

模块标准

现在的前端模块化标准主要有两种:cmd、amd.

CMD

CMD在模块定义当中有三个变量,分别是require,exports,module.除了这三个变量可以辨识CMD
外,define函数还有一个公有属性define.cmd。我们也可以监测这个值来判断是否是cmd。
如果想要对外提供接口的话,可以将接口绑到exports(module.exports)。

function MyModule() { // ...}
if(typeof module !== `undefined` && typeof exports === `object` && define.cmd) {
 module.exports = MyModule;
}

如果需要支持除了cmd之外的其他符合CommonJS的标准,请去掉define.cmd

AMD

AMD规范中,define函数同样有一个公有属性define.amd。
AMD中的参数便是这个模块的依赖,那么如何在AMD中提供接口呢?它是返回一个对象,这个对象就作为模块的接口,故我们可以这样写:

function MyModule() {
 // ...
}
if(typeof define === `function` && define.amd) { 
define(function() { 
return MyModule; 
});
}

总结

我们除了提供AMD模块的接口,CMD模块接口,还得提供原生的JS接口,一个直接可以用的代码:

;(function(){
 function MyModule() {
     // ... 
  }
 var moduleName = MyModule;
 if (typeof module !== 'undefined' && typeof exports === 'object' && define.cmd) { 
      module.exports = moduleName;  
  } else if (typeof define === 'function' && define.amd) {  

       define(function() {    return moduleName;  });   

  } else {
       this.moduleName = moduleName;    
  }
}).call(function() { 

       return this || (typeof window !== 'undefined' ? window : global);
});

你可能感兴趣的:(JavaScript如何让你的插件兼容AMD,CMD和原生JS)