高级前端
js
【Q473】关于模块化,什么是 amd 和 umd

关于模块化,什么是 amd 和 umd

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 481 (opens in a new tab)

Author 回答者: shfshanyue (opens in a new tab)

amd 是一种浏览器中的模块格式,关键字为 definecjs 是一种 Node 中的模块格式,也是广为人所熟悉的 require/exports

umdamdcjs 两种格式的兼容。既可以跑在浏览器,又可以跑在 Node 中

amd

define(["jquery", "underscore"], function ($, _) {});

umd

(function (root, factory) {
  if (typeof define === "function" && define.amd) {
    // AMD
    define(["jquery"], factory);
  } else if (typeof exports === "object") {
    // CommonJS
    module.exports = factory(require("jquery"));
  } else {
    // 全局变量
    root.returnExports = factory(root.jQuery);
  }
})(this, function ($) {
  // ...
});