Reputation: 702
I have the following.
require([ 'a', 'b' ], function() {
if(x){
require([ 'c', 'd' ], function( ) {});
}
});
c
will always be loaded with d
. Is there anyway to make the optimizer optimize c
and d
so that they will load as one file?
EDIT:
Also im using r.js as the optimizer. And the modules for my build script look something like this.
modules: [
{
name: "main",
},
{
name: "c",
include: ["d"]
}
]
This will include d
in c
, but both c
and d
are still loaded at runtime.
Upvotes: 1
Views: 1482
Reputation: 702
I got the answer here
You can set up a path mapping in production to inform RequireJS that d
is located at c
.
Simply do:
paths: {
'd': 'c'
}
Upvotes: 1
Reputation: 13181
r.js
(I'm assuming that's what you mean by "optimizer") won't touch c
and d
unless you explicitly ask it to ["You can always explicitly add modules that are not found via the optimizer's static analysis by using the include option." - from RequireJS docs]. If you do that they'll end up in the optimized output and will be loaded at runtime together with a
and b
and the rest of the code (even if x
is false
and the require
block is never reached).
If you don't, r.js
will skip that block and RequireJS
will only resolve c
and d
at runtime (if x
is true
), when it's too late to do any optimizations or concatenations.
RE: the edit
The correct way to force including c
and d
in main
would be:
modules: [ {
name: "main",
include: ["c", "d"]
} ]
This means: "include everything main.js
requires explicitly but also add c.js
and d.js
"
RE: the comment:
Oh, you're right, your configuration will also create an optimised c.js
that includes both c
and d
but RequireJS
will load the 'standalone' d
anyway. Strangely, it will still use the d
from the optimised file and won't even evaluate the standalone d.js
(checked by editing contents of optimised c.js
and d.js
). I guess RequireJS requests all listed dependencies immediately since it has no way of knowing that loading c
will satifsy the d
dependency (this is only known after the module is loaded and processed). That makes sense because the only other option would be request the files sequentially, one by one - that would be a bottleneck.
Upvotes: 2