Search code examples
javascriptrequirejsjs-amd

How can I load multiple optimized requirejs modules dynamically in a production env?


I've started to play with require js on a dummy project. I now want to use the r.js script to build my project for production.

The context is this:

  • Main file called start.js is:

    require([/* some stuff */], function (){ /* app logic */ });
    

    which has an if that decides what I should require based on some condition.

  • The required files are either ModuleA or ModuleB

  • Both ModuleA and ModuleB have dependencies.

    define([/*some deps*/], function(dep1, dep2...) { 
        /* app logic */ 
        return { /* interface */
    }
    
  • Everything works fine in development mode, before optimization and module concatenation.

  • When building with r.js I specify as module targets the following : modules : [ { name : "start" }, { name : "ModuleA" }, { name : "ModuleB" } ]

The problem is that my ModuleA becomes :

 define(dep1 ..);
 define(dep2 ..);
 define(ModuleA ..);

But nothings loads from ModuleA. The code from ModeulA in development loads and executes, the code after building loads but does not run.

How could I fix this problem?

UPDATE

http://pastebin.com/p1xUcY0A --> start.js

http://pastebin.com/dXa6PtpX --> ModuleA js-animation.js

http://pastebin.com/xcCvhLrT --> ModuleB css-animation.js no deps.

http://pastebin.com/j51V5kMt --> The r.js config file used when running the optimizer.

http://pastebin.com/UVkWjwe9 --> How the js-animation.js looks after running r.js. This is the file that has problems. I don't get the js-animation module from this file. The require does not return my js-animation object.

Edit:

After removing the .js at the end of the module definitions and in from start js, the optimized start.js is http://pastebin.com/LfaLkJaT and the js-animations module is http://pastebin.com/qwnpkCC6. In chrome, I get this error in my console http://pastebin.com/Hq7HGcmm


Solution

  • It seems this is problematic with the current require.js implementation. The way around it was to create a global mediator or mediator module and have all dynamically loaded modules call the mediator and announce themselves via an event. This worked for me.