johni johni - 1 year ago 173
Javascript Question

Generate RequireJS "bundles" config dynamically with Grunt

  1. According to the RequireJS API, the
    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
    of course, how can I generate the
    configuration dynamically, according to the actual bundling? e.g. if module
    was bundled to
    , then it should be added to the list of modules of the

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

Any suggestions?

Answer Source

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
//( 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:
//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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download