johni johni - 1 month ago 11
Javascript Question

Generate RequireJS "bundles" config dynamically with Grunt


  1. According to the RequireJS API, the
    bundles
    configuration property is used to map modules to their bundle files (in production mode, assuming you have multiple bundles on large-scale projects).

  2. I use Grunt for bundling with
    r.js
    of course, how can I generate the
    bundle
    configuration dynamically, according to the actual bundling? e.g. if module
    angular
    was bundled to
    common.js
    , then it should be added to the list of modules of the
    common
    bundle.



This part of requirejs configuration should not be maintained manually, as it will result in many mistakes.

Any suggestions?

Answer

Version 2.2.0 of RequireJS introduced a new optimizer option to write out a bundles option that is generated from the build:

//Introduced in 2.2.0. Path to file to write out bundles config
//(http://requirejs.org/docs/api.html#config-bundles) found in the module
//layers built by the optimizer. The path is relative to the "dir" config's
//path. Only applies to full project optimization:
//http://requirejs.org/docs/optimization.html#wholeproject
//Only use if the optimized layers are grouped more intricately then just
//a simple optimization of main app entry points. The file path specified
//should be to one that has the top level requirejs.config() call that sets
//up the loader. If using "mainConfigFile", then this path likely should be
//the path to that file where it is placed in the "dir" output directory.
bundlesConfigOutFile: 'some/path/to/main.js',

If the option above does not work for you, then you'll have to do what I did and roll your own code to generate a proper value for bundles.