How does AMD (specifically RequireJs) handle depen

2019-04-06 05:16发布

I have my main initialization script which calls require() and one of the dependencies is a utilities framework, but some of the other modules that I'm specifying via require() also themselves have defined this framework as a dependency.

For example (init.js):

require(['module-a', 'module-b', 'module-c'], function(a, b, c){
    // where module-c is the framework
});

And then in 'module-a' I have:

define(['module-c'], function(c){
    // utilize module-c framework
});

So how does AMD/RequireJs handle this scenario, does it load the same framework twice?

Any help appreciated.

Kind regards, Mark

2条回答
贪生不怕死
2楼-- · 2019-04-06 05:56

Incase its useful to others - Here's a situation I came across where a module was loaded twice:

For the following project structure:

~/prj/js/app/fileA.js
~/prj/js/app/util/fileB.js
~/prj/js/ext/publisher.js

where the RequireJs baseurl is ~/prj/js/app

fileA.js refers to the external (ext) dependancy publisher.js as:

//fileA:
define(['../ext/publisher'], function(){});

But fileB.js refers to the same dependancy with a different path:

//fileB:
define(['../../ext/publisher'], function(){});

In short, for both files, the dependency paths are different although the dependancy is in the same location. In this case, publisher.js gets loaded twice.

Use Firebug's Net tab to see it loading twice:

dependency.js being loaded twice (firebug)

This is easily fixed using paths to configure the external folder path (as explained in the require_js docs):

requirejs.config({
    paths: {ext: '../ext'}
});

After setting paths, the dependency is loaded just once with fileA.js and fileB.js both using the same dependency path as follows:

//fileA:
define(['ext/publisher'], function(){});

and

//fileB:
define(['ext/publisher'], function(){});
查看更多
Evening l夕情丶
3楼-- · 2019-04-06 06:04

It will only be loaded once, both of the above modules will get the same module value for 'module-c'.

查看更多
登录 后发表回答