I have a function in moduleA that must run prior to the loading of moduleB. ModuleA isn't dependent on any other module and moduleB has some dependencies (moduleC for instance). The following code does it and works fine when it's not optimized:
main-config.js
require.config({
paths: {
moduleA: 'modules/moduleA',
moduleB: "modules/moduleB",
moduleC: "modules/moduleC",
}
});
require(['moduleA'], function (moduleA) {
moduleA.init(function () {
require(['moduleB'], function (moduleB) {
moduleB.start();
});
});
});
However, when optimizing it with r.js, things are getting messed. The output of the r.js optimizer is:
Tracing dependencies for: ../scripts/main-config
Uglifying file: C:/.../scripts/main-config.js
C:/.../scripts/main-config.js
----------------
C:/.../scripts/libs/require/require.js
C:/.../scripts/modules/moduleA.js
C:/.../scripts/main-config.js
Which means that only the 3 modules - require, moduleA and main-config - are uglified together to 1 minimized file. All of moduleB's dependencies (such as moduleC) are missing from the output file.
Changing the config file to the following, will include all of moduleB's dependencies in the output file, but it will not get the needed result since it parses moduleB before moduleA's init function:
require(['moduleA','moduleB'], function (moduleA, moduleB) {
moduleA.init(function () {
moduleB.start();
});
});
I want moduleB to be parsed later, only after moduleA's init function (moduleB contains some immediate functions).
How can I get all the dependency tree to be included in the result file, but with my needed behavior (parse&run moduleB after a function of moduleA finishes)? Thanks.
This happens because require
for moduleB
is nested and potentially dynamic; by default r.js
won't include such dependencies in the output. To override this default behaviour you can set findNestedDependencies
to true
(more details in the example buildconfig file).
Alternatively, if you don't want to change this flag for the whole project and you only want to make an exception for this single dependency, you can add the module
element to your buildconfig:
modules: [{
name: "main-config",
// forces moduleB to be included
include: ["moduleB"]
},
// ...