为了解决的问题
1 | <script src="file1.js"></script> |
异步模块定义 (Asynchronous Module Definition as AMD)
dom/events.js 定义模块
1 | define({ |
main.js 使用 RequireJS 加载模块,模块不需要后缀
1 | require(["dom/events"], function (event) { |
在 main.js 使用模块
1 | require(["dom/events"], function (events) { |
index.html
1 |
|
让模块稍微复杂点 dom/events.js
1 | define(function () { |
再写个 Array.prototype.forEach 兼容方法 utils/array.js
1 | define(function () { |
同样使这个模块稍微复杂点
1 | define(["utils/array"], function (array) { |
在 dom/events.js 中使用 utils/array.js,添加依赖关系
1 | define(["utils/array"], function (array) { |
在 main.js 使用添加了 utils/array.js 依赖的 dom/events.js
1 | event.click(elem, function () { |
模块的名字不指定则为模块默认名
1 | require(["utils/array"], function () { |
main.js 完整配置
1 | requirejs.config({ |
RequireJS 插件
以 text plugin 为例
把 text.js 放在 main.js 同级目录,在 main.js 请求
1 | require(["text!templates/list.html", "libs/underscore"], function (listTpl) { |
templates/list.html 模板用的是 Rails html 模板语法,因为 underscorejs 的 _.template() 默认这种写法
1 | <ul> |

优化工具
app.build.js
1 | ({ |
r.js 默认优化配置,可以选择性改变
1 | buildBaseConfig = { |
开始 build 优化
1 | node /path/to/r.js -o app.build.js |
输出
1 | Optimizing (standard) CSS file: /Users/andrew/Sites/sample-build/css/custom.css |