【发布时间】:2014-07-16 14:14:02
【问题描述】:
我想定义一个模块,它除了需要其他模块之外什么都不做,以确保它们被包含在内。像这样:
File: common.js
define(['routes/index_route', 'routes/guides_route']);```
r.js 输出为:
define(['routes/index_route', 'routes/guides_route']);
这是错误的,因为它应该输出一个命名模块。
但是,如果我用这样的虚拟函数回调定义它:
File common.js
define(['routes/index_route', 'routes/guides_route'], function() {});
r.js 正确输出。
define('routes/common',['routes/index_route', 'routes/guides_route'],
function() {});
是否可以将一个模块定义为唯一需要类似这样的其他模块的目的?
为什么 r.js 会这样?
编辑
我在使用 amd 术语时遇到问题,所以我将定义我的问题。
我有一个包含所有模块的 router.js。
File: router.js
define(['routes/index_route', 'routes/guides_route', 'routes/other_route'],
function() {
});
我包括所有这些routes ('index_route, guides_route'),但我并不需要任何参考。所以而不是包括一堆
routes 像这样在 router.js 中,我想将所有这些 routes 包含在一个单独的文件中,并将该文件包含在 router.js 中。
File: router.js
define(['routes/common'], function() {});
File: routes/common.js
define(['routes/index_route', 'routes/guides_route', 'routes/other_route']);
那么就出现了上面的问题。
TL;DR 我认为您混淆了 require 和 define 是什么。以及 r.js 的用途。
虽然require(['module'], function() {}) 和define(['module'], function() {}) 之间的区别是
require 函数被立即调用,define 函数只有在其他模块需要它时才会被调用。
所以
if you want to request modules you need to use require insead of define 没有意义。
TL;DR 请告诉我两者之间的区别:
define(['module']);
define(['module'], function() {})
就优化器如何对它们进行操作而言。这将告诉我为什么优化器在两种情况下输出不同。
define(['module']);
define('filename', ['module']);
如果我陷入某种陷阱,请提供更多信息,否则请不要进一步混淆我。
【问题讨论】:
-
当你说“这是错误的,因为它应该输出一个命名模块。”,为什么这很重要?你是说当优化器没有将模块命名为
routes/common时define(['routes/common'], function() {});不起作用? -
@sahbeewah 当优化器没有命名模块时,它在浏览器中找不到
routes/common模块并给出错误。如果我省略function() {},它将不起作用,否则它会正确命名模块。
标签: javascript ruby-on-rails node.js requirejs amd