一下三块均以 foo.js 为示例文件名,以 jquery,underscore 为需求组件
adm:异步模块规范, requirejs 的支持格式
// 文件名: foo.js
define(['jquery', 'underscore'], function ($, _) {
// 方法
function a(){}; // 私有方法,因为没有被返回(见下面)
function b(){}; // 公共方法,因为被返回了
function c(){}; // 公共方法,因为被返回了
// 暴露公共方法
return {
b: b,
c: c
}
});
commonjs:node 的支持格式
// 文件名: foo.js
var $ = require('jquery');
var _ = require('underscore');
// methods
function a(){}; // 私有方法,因为它没在module.exports中 (见下面)
function b(){}; // 公共方法,因为它在module.exports中定义了
function c(){}; // 公共方法,因为它在module.exports中定义了
// 暴露公共方法
module.exports = {
b: b,
c: c
};
umd:通用模式,支持以上两种格式,切可以支持老式的 “全局变量” 规范
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// amd
define(['jquery', 'underscore'], factory);
} else if (typeof exports === 'object') {
// node, commonjs之类的
module.exports = factory(require('jquery'), require('underscore'));
} else {
// 浏览器全局变量(root 即 window)
root.returnexports = factory(root.jquery, root._);
}
}(this, function ($, _) {
// 方法
function a(){}; // 私有方法,因为它没被返回 (见下面)
function b(){}; // 公共方法,因为被返回了
function c(){}; // 公共方法,因为被返回了
// 暴露公共方法
return {
b: b,
c: c
}
}));
以上就是关于amd和cmd以及umd三种模块的规范以及写法格式详解的详细内容。