r.js到底是做什么的?

5

我试图了解流行的r.js的好处。

它似乎...

  • 连接一组手动选择的JavaScript文件
  • 缩小/最小化组合代码
  • 对CSS文件执行类似操作(将它们合并)

此外,(它与通用的组合/缩小工具不同之处在于)它似乎会...

  • 将Node风格的require()模块转换为AMD风格的模块
  • 为匿名模块命名(例如:define(['dependency'], function(){...})
  • 提供对加载程序插件的某些支持,例如内联CSS文件

它似乎没有...

  • 分析和自动解决文件中发现的依赖关系(例如,包含文件foo.js到包中只是因为r.js找到一个define(["foo"], ...))

这正确吗?还是我错过了什么?


哦,我的编辑是否不正确,你真的是要“将文件foo.js包含在包中,只因为r.js找到了**define(["foo"], ...)***”?如果代码已经存在(foo已被定义),我看不出为什么你想要加载foo.js文件。 - Bergi
RequireJS / Optimization:"[r.js]将相关的脚本合并到构建层中,并对其进行缩小。依赖图本身仍在运行时解决,所有模块都被简单地推在一起,因此不需要单独的资源获取。" - user2864740
@Bergi:不了解您的编辑,但是是的,我想确保r.js不会自动解析任何依赖项是正确的。我并不是说它应该这样做。只是我觉得r.js进行了一些复杂的JavaScript解析/处理,并且希望确保我理解该过程中的所有步骤。 - Udo G
1
@user2864740:所以,对于已经采用AMD风格的模块,r.js没有进行任何特殊处理,这些处理都可以由经典的组合器/缩小器完成?(无意批评) - Udo G
1
@UdoG 我的意思是:通常每个文件的模块依赖关系都会被包含,除非被排除在外,但对象图/加载顺序不会被包含。 - user2864740
@UdoG 如果没有使用 r.js,您将如何处理任何非 AMD 依赖项? - Dannyboy
1个回答

7
你错了,因为r.js会自动解析依赖项。如果你有一个包含以下内容的main.js文件:
define(["foo"], function (foo) {
});

如果您请求 r.js 创建一个优化的模块,以从 main.js 中产生一个优化的模块,它将会把模块 foo 的代码包含在构建中。

需要注意的是:

  1. It is possible to tell r.js to exclude modules. So if a module you think should be in an optimized bundle is absent, it may be that it has been excluded. (You know how you are using r.js but if you use a bundle produced by someone else and you wonder, then this may be the answer: they specifically excluded a dependency from the build.)

  2. r.js does not find nested dependencies unless you tell it to. For instance:

    define(function () {
        require(["foo"], function (foo) {
        });
    });
    

    r.js won't find that foo is required unless you set findNestedDepencencies to true in your build config.

  3. r.js can find only dependencies that are specified in the form of a list of string placed as a literal in the location where the require and define calls expect dependencies. So if you do:

    define(function () {
        var deps = ["foo"];
        require(deps, function (foo) {
        });
    });
    

    Then r.js won't know that foo is a dependency, because in require(deps, ... your dependencies appear as a symbol reference, not as a list of strings. You would have to specify foo as a dependency manually in the build configuration. There's no flag to turn on to make r.js find these cases.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接