js模块AMD兼容写法总结

2017-12-06 | 4,505浏览 | 0评论 | 标签:amd require.js 模块

js模块AMD兼容写法总结

本文只针对浏览器端require.js方式加载模块进行总结。下文的源码是精简版,不能直接运行,完整源码参见DEMO 或者https://github.com/denghao123/js-module

个人能力有限,仅供参考,并非最佳实践。

涉及记忆点:

  1. require.js加载标准模块
  2. reqiure.js加载非标准模块
  3. AMD/commonJs兼容写法
  4. jQuery插件AMD兼容写法
  5. 多页面按需加载模块

一、 require.js加载标准模块

模块定义(amd.js):
define([], function() {
  return {
    hello: function() {
      console.log("我是AMD规范写法")
    }
  }
});

配置(config.js):
require.config({    
  paths: {      
    "amd": "./assets/js/amd"
  }
});

模块调用(page1.js):
requirejs(["amd"], function(o) {
   o.hello();
});


二、 reqiure.js加载非标准模块

模块定义(funs.js):
function fn1() {
  console.log("我是fn1()")
}

function fn2() {
  console.log("我是fn2()")
}

配置(config.js):
require.config({    
  shim: {
    "funs": {
      init: function() {
        return {
          fn1: fn1,
          fn2: fn2
        }
      }
    }
  }
});

模块调用(page2.js):
requirejs(["funs"], function(o) {
   o.fn1();
   o.fn2();
});

三、 AMD/commonJs兼容写法

模块定义(commonjs.js):
(function() {
  var Obj = {
    name: "DH",
    say: function() {
      console.log("你好")
    }
  }
  if (typeof module !== "undefined" && typeof exports === "object") {
    module.exports = Obj;
  } else if (typeof define === "function" && (define.amd || define.cmd)) {
    define(function() {
      return Obj;
    });
  } else {
    this.Obj = Obj;
  }
}).call(this || (typeof window !== "undefined" ? window : global));

配置(config.js):
require.config({    
  paths: {      
    "commonjs": "./assets/js/commonjs"
  }
});

模块调用(page3.js):
requirejs(["commonjs"], function(o) {
   console.log(o.name);
   o.say();
});

四、 jQuery插件AMD兼容写法

模块定义(jquery.say.js):
(function(factory) {
  if (typeof define === "function" && define.amd) {
    define(["jquery"], factory);
  } else {
    factory(jQuery);
  }
}(function($) {
  
  $.extend({
    say: function() {
      console.log("jquery say")
    }
  })

}));

配置(config.js):
require.config({    
  baseUrl: "./assets/js",
  paths: {      
    "jquery": "jquery.min",
    "jquery-say": "jquery.say"
  }
})

模块调用(page4.js):
requirejs(["jquery","jquery-say"], function() {
   $.say();
});

五、 多页面按需加载模块

html按需引用js:
page1.html
<script src="./require.js" defer async="true" data-main="./assets/js/page1"></script>
page2.html
<script src="./require.js" defer async="true" data-main="./assets/js/page2"></script>

共公配置(config.js):
require.config({    
  baseUrl: "./assets/js",
  paths: {      
    "jquery": "jquery.min",
    "jquery-say": "jquery.say",
    "say": "jquery.say",
    "amd": "amd",
    "commonjs": "commonjs"
  },
  shim: {
    "funs": {
      init: function() {
        return {
          fn1: fn1,
          fn2: fn2
        }
      }
    }
  }
});

模块调用(page1.js):
requirejs(['../../config'], function() {
  requirejs(['amd'], function(o) {
     o.hello();
  });
});

完整源码参见DEMO或者 https://github.com/denghao123/js-module

(本篇完。有疑问欢迎留言探讨)

留言:

*

* (方便回复通知)

打赏
编辑代码 运行结果
退出