Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Requirejs - Share the same dependency through different modules

Imagine this project scaffold:

  • utils.js
  • module1/controllers.js
  • module1/services.js
  • module2/controllers.js
  • module2/services.js

utils.js

define([], function(){  /* My utils functions */ });

module1/controllers.js

define(['../utils'], function(utils){  /* Module1 stuff */ });

module2/controllers.js

define(['../utils'], function(utils){  /* Module2 stuff */ });

This works very well in a non-optimization context, because utils.js is downloaded only once, no matter whether is from module1 or module2. However I need to optimize and package each module in a JS file.

In order to get this, I add a main.js file in each module, for example:

module1/main.js

define(['./controllers', './services.js'], function(){});

Now I start playing with the optimization tool, this is my app.build.js

...
modules: [
        { name: "module1/main" },
        { name: "module2/main" },
    ]
...

Ok, I get the behaviour I wanted, but I see that both modules include the utils.js code. This behaviour is right because you can't guarantee the loading order.

So, these are my questions:

  1. Does exist any smart solution for this?
  2. If this can't be skipped, does anybody know how requirejs works under the hood? Could this strategy generate any kind of problems?
like image 989
Ivan Guardado Avatar asked Feb 06 '26 05:02

Ivan Guardado


1 Answers

Finally I got the answer using the exclude option in the build script:

...
modules:[
  { name: 'utils' },
  { name: 'module1/main', exclude: ['utils'] }
  { name: 'module2/main', exclude: ['utils'] }
]
...

This way I create a separated module for the utils and avoid to include it in the other modules code using the option "exclude". This method forces you to write this kind of "global" dependencies manually, but it works :)

like image 87
Ivan Guardado Avatar answered Feb 09 '26 06:02

Ivan Guardado



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!