3

So the situation is the following:

I have a bunch of page specific js files which I'm optimizing using r.js.

99% of them define a a module called core.js as a dependency. Core has 5 dependencies of it's own.

I wanted to leverage caching by excluding core from the optimised versions of the page js files.

So in my build.js I tried something along the lines of:

modules: [
  {
     name : 'modules/core'
  },
  {
     name: 'homepage',
     exclude : ['modules/core']
  }
]

When I run the optimiser it optimises both modules/core & homepage just fine.

Going to a page that uses homepage.js the issue is that: core.js & it's dependencies are being loaded in individually, leading to 7 requests instead of 2.

In the above example, what I'm trying to achieve is: have homepage.js and it's dependencies optimised into a single file and have it load in an optimised version of core.js rather then loading in the core.js and it's dependencies separately.

Is that even possible?

4

1 回答 1

2

在构建之后,您有两个选择:

1)修改顶级加载,以便在任何其他加载之前加载模块/核心:

require(['modules/core'], function () {
  //Now do normal require stuff in here
});

如果您在主页完​​成加载之前看到其模块被请求,请在主页中使用另一个嵌套的 require() 调用。

2) 插入一个 require.config 块,将 core 中的所有模块指向 core 文件。当多个模块 ID 都指向它时,requirejs 只会获取一次 core.js 文件:

require.config({
  paths: {
    'mod/one': 'modules/core',
    'mod/two', 'modules/core',
    ...
  }
});

或者查看这种示例项目,该项目设置加载一个公共层,然后加载一个特定于页面的层,但无需在构建后进行源代码修改即可工作(仅使用 #1 的变体,但将其设置为在源代码中工作形式):

https://github.com/requirejs/example-multipage

于 2013-03-15T18:41:26.593 回答