Require JS - define模块定义

CMD (Common Module Definition)
在 CMD 规范中,一个模块就是一个文件。代码的书写格式如下:

define(factory);

define 是一个全局函数,用来定义模块。

1. factory为函数时,表示模块的构造方法:

1
2
3
define(function(require, exports, module) {
// 模块代码
});

执行该构造方法,可以得到模块向外提供的接口。
factory 为对象、字符串时,表示模块的接口就是该对象、字符串

1
define({ "foo": "bar" });

也可以通过字符串定义模板模块:

1
define('I am a template. My name is {{name}}.');

2. define(id, deps, factory?)

字符串 id 表示模块标识,数组 deps 是模块依赖

1
2
3
define('hello', ['jquery'], function(require, exports, module) {
// 模块代码
});

factory参数可以省略。省略时,表示声明依赖关系。
在开发阶段,推荐不要手写 id 和 deps 参数,因为这两个参数可以在构建阶段通过工具自动生成。

注意:带 id 和 deps 参数的 define 用法不属于 CMD 规范,而属于 Modules/Transport 规范。

3. require Function

require接受module-name(id)作为唯一参数,用来获取其他模块提供的接口

1
2
3
4
5
6
define(function(require, exports) {
// 获取模块 a 的接口
var a = require('./a');
// 调用模块 a 的方法
a.doSomething();
});

4. exports Object

exports 是一个对象,用来向外提供模块接口。

1
2
3
4
5
6
7
define(function(require, exports) {
// 对外提供 foo 属性
exports.foo = 'bar';
// 对外提供 doSomething 方法
exports.doSomething = function() {};

});

除了给exports对象增加成员,还可以使用return直接向外提供接口。

1
2
3
4
5
6
7
define(function(require) {
// 通过 return 直接提供接口
return {
foo: 'bar',
doSomething: function() {};
};
});

TBC


ref: https://blog.csdn.net/cpf506497746/article/details/8832317