当前位置:   article > 正文

兼容多种模块规范(AMD,CMD,Node)的代码

兼容amd、cmd、node

前言

昨天,公司同事问了我如下一个问题:

clipboard.png

说他在看一个插件时,看到了源码结构如截图所示,他知道(function(){})()是一种立即执行函数,但是在截图中,最后的那个圆括号里又写了一个函数function($,ChineseDistricts){...},这个函数暂且称为“匿名函数1”,function (factory){...}暂且称为“”匿名函数2”,意思是不是:把匿名函数1传入到匿名函数2的参数factory中,然后检测当前环境。如果检测到了全局环境中存在exports对象,则证明是node环境,如果是node环境,则用factory(require('jquery'), require('ChineseDistricts'))这个方法来执行匿名函数1,因为Node是基于模块的,所以在Node中要使用这个插件的话,必须用require()方法把匿名函数2中需要的参数"$"和"ChineseDistricts"以模块的方式给引用进来?

看到截图的代码和它的疑问,请接着往下看......

一、兼容多种模块规范(AMD,CMD,Node)的代码

在JavaScript模块化开发中,为了让同一个模块可以运行在前后端,以及兼容多种模块规范(AMD,CMD,Node),类库开发者需要将类库代码包装在一个闭包内。

1.AMD规范

AMD,即“异步模块定义”。主要实现比如: RequireJS。

其模块引用方式如下:define(id?,dependencies?,factory);

其中,id及依赖是可选的。其与CommonJS方式相似的地方在于factory的内容就是实际代码的内容,下面是一个简单的例子:

  1. define(function(){
  2. var exports = {};
  3. exports.say = function(){
  4. alert('hello');
  5. };
  6. return exports;
  7. });

2.CMD规范

CMD规范,与AMD类似,区别主要在于定义模块和依赖引入的地方。主要实现比如: SeaJS。

主要区别是:AMD需要在声明模块时指定所有的依赖,通过形参传递依赖到模块内容中。

  1. define(['dep1','dep2'],function(dep1,dep2){
  2. return function(){};
  3. });

与AMD相比,CMD更接近Node对CommonJS规范的定义:

define(factory);

在依赖部分,CMD支持动态引入,如下:

  1. define(function(require,exports,module){
  2. // Todo
  3. });

require、exports、module通过形参传递给模块,在需要依赖模块时,随时调用require引入即可。

3.CommonJS的模块实现

CommonJS的模块引用使用require,如下:

var http = require('http');

4.Node的模块实现

在Node中引入模块,需要经过下面3个步骤:路径分析;文件定位;编译执行。主要用require()方法来查找模块。

5.兼容多种模块规范

为了让同一个模块可以运行在前后端,在开发过程中需要考虑兼容前后端问题,以下代码演示如何将hello()方法定义到不同的运行环境中,它能够兼容AMD、CMD、Node以及常见的浏览器环境中:

  1. ;(function (name, definition) {
  2. // 检测上下文环境是否为AMD或CMD
  3. var hasDefine = typeof define === 'function',
  4. // 检查上下文环境是否为Node
  5. hasExports = typeof module !== 'undefined' && module.exports;
  6. if (hasDefine) {
  7. // AMD环境或CMD环境
  8. define(definition);
  9. } else if (hasExports) {
  10. // 定义为普通Node模块
  11. module.exports = definition();
  12. } else {
  13. // 将模块的执行结果挂在window变量中,在浏览器中this指向window对象
  14. this[name] = definition();
  15. }
  16. })('hello', function () {
  17. var hello = function () {};
  18. return hello;
  19. });

二、如何封装Node.js和前端通用的模块

在Node.js中对模块载入和执行进行了包装,使得模块文件中的变量在一个闭包中,不会污染全局变量,和他人冲突。

前端模块通常是我们开发人员为了避免和他人冲突才把模块代码放置在一个闭包中。

如何封装Node.js和前端通用的模块,我们可以参考Underscore.js 实现,他就是一个Node.js和前端通用的功能函数模块,查看代码:

  1. // Create a safe reference to the Underscore object for use below.
  2. var _ = function(obj) {
  3. if (obj instanceof _) return obj;
  4. if (!(this instanceof _)) return new _(obj);
  5. this._wrapped = obj;
  6. };
  7. // Export the Underscore object for **Node.js**, with
  8. // backwards-compatibility for the old `require()` API. If we're in
  9. // the browser, add `_` as a global object via a string identifier,
  10. // for Closure Compiler "advanced" mode.
  11. if (typeof exports !== 'undefined') {
  12. if (typeof module !== 'undefined' && module.exports) {
  13. exports = module.exports = _;
  14. }
  15. exports._ = _;
  16. } else {
  17. root._ = _;
  18. }

通过判断exports是否存在来决定将局部变量 _ 赋值给exports,向后兼容旧的require() API,如果在浏览器中,通过一个字符串标识符“_”作为一个全局对象;完整的闭包如下:

  1. (function() {
  2. // Baseline setup
  3. // --------------
  4. // Establish the root object, `window` in the browser, or `exports` on the server.
  5. var root = this;
  6. // Create a safe reference to the Underscore object for use below.
  7. var _ = function(obj) {
  8. if (obj instanceof _) return obj;
  9. if (!(this instanceof _)) return new _(obj);
  10. this._wrapped = obj;
  11. };
  12. // Export the Underscore object for **Node.js**, with
  13. // backwards-compatibility for the old `require()` API. If we're in
  14. // the browser, add `_` as a global object via a string identifier,
  15. // for Closure Compiler "advanced" mode.
  16. if (typeof exports !== 'undefined') {
  17. if (typeof module !== 'undefined' && module.exports) {
  18. exports = module.exports = _;
  19. }
  20. exports._ = _;
  21. } else {
  22. root._ = _;
  23. }
  24. }).call(this);

通过function定义构建了一个闭包,call(this)是将function在this对象下调用,以避免内部变量污染到全局作用域。浏览器中,this指向的是全局对象(window对象),将“_”变量赋在全局对象上“root._”,以供外部调用。

和Underscore.js 类似的Lo-Dash,也是使用了类似的方案,只是兼容了AMD模块载入的兼容:

  1. ;(function() {
  2. /** Used as a safe reference for `undefined` in pre ES5 environments */
  3. var undefined;
  4. /** Used to determine if values are of the language type Object */
  5. var objectTypes = {
  6. 'boolean': false,
  7. 'function': true,
  8. 'object': true,
  9. 'number': false,
  10. 'string': false,
  11. 'undefined': false
  12. };
  13. /** Used as a reference to the global object */
  14. var root = (objectTypes[typeof window] && window) || this;
  15. /** Detect free variable `exports` */
  16. var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
  17. /** Detect free variable `module` */
  18. var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;
  19. /** Detect the popular CommonJS extension `module.exports` */
  20. var moduleExports = freeModule && freeModule.exports === freeExports && freeExports;
  21. /*--------------------------------------------------------------------------*/
  22. // expose Lo-Dash
  23. var _ = runInContext();
  24. // some AMD build optimizers, like r.js, check for condition patterns like the following:
  25. if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
  26. // Expose Lo-Dash to the global object even when an AMD loader is present in
  27. // case Lo-Dash was injected by a third-party script and not intended to be
  28. // loaded as a module. The global assignment can be reverted in the Lo-Dash
  29. // module by its `noConflict()` method.
  30. root._ = _;
  31. // define as an anonymous module so, through path mapping, it can be
  32. // referenced as the "underscore" module
  33. define(function() {
  34. return _;
  35. });
  36. }
  37. // check for `exports` after `define` in case a build optimizer adds an `exports` object
  38. else if (freeExports && freeModule) {
  39. // in Node.js or RingoJS
  40. if (moduleExports) {
  41. (freeModule.exports = _)._ = _;
  42. }
  43. // in Narwhal or Rhino -require
  44. else {
  45. freeExports._ = _;
  46. }
  47. }
  48. else {
  49. // in a browser or Rhino
  50. root._ = _;
  51. }
  52. }.call(this));

再来看看Moment.js的封装闭包主要代码:

  1. (function (undefined) {
  2. var moment;
  3. // check for nodeJS
  4. var hasModule = (typeof module !== 'undefined' && module.exports);
  5. /************************************
  6. Exposing Moment
  7. ************************************/
  8. function makeGlobal(deprecate) {
  9. var warned = false, local_moment = moment;
  10. /*global ender:false */
  11. if (typeof ender !== 'undefined') {
  12. return;
  13. }
  14. // here, `this` means `window` in the browser, or `global` on the server
  15. // add `moment` as a global object via a string identifier,
  16. // for Closure Compiler "advanced" mode
  17. if (deprecate) {
  18. this.moment = function () {
  19. if (!warned && console && console.warn) {
  20. warned = true;
  21. console.warn(
  22. "Accessing Moment through the global scope is " +
  23. "deprecated, and will be removed in an upcoming " +
  24. "release.");
  25. }
  26. return local_moment.apply(null, arguments);
  27. };
  28. } else {
  29. this['moment'] = moment;
  30. }
  31. }
  32. // CommonJS module is defined
  33. if (hasModule) {
  34. module.exports = moment;
  35. makeGlobal(true);
  36. } else if (typeof define === "function" && define.amd) {
  37. define("moment", function (require, exports, module) {
  38. if (module.config().noGlobal !== true) {
  39. // If user provided noGlobal, he is aware of global
  40. makeGlobal(module.config().noGlobal === undefined);
  41. }
  42. return moment;
  43. });
  44. } else {
  45. makeGlobal();
  46. }
  47. }).call(this);

从上面的几个例子可以看出,在封装Node.js和前端通用的模块时,可以使用以下逻辑:

  1. if (typeof exports !== "undefined") {
  2. exports.** = **;
  3. } else {
  4. this.** = **;
  5. }

即,如果exports对象存在,则将局部变量装载在exports对象上,如果不存在,则装载在全局对象上。如果加上ADM规范的兼容性,那么多加一句判断:

if (typeof define === "function" && define.amd){}

参考链接:
1.http://www.css88.com/archives...
2.http://www.css88.com/archives...

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/运维做开发/article/detail/748217
推荐阅读
相关标签
  

闽ICP备14008679号