0
votes

Following this RequireJS example I'm trying to have a single file for all vendor js assets like jquery and foundation, whilst loading page specific code in other modules.

While I can build and copy the js successfully (using grunt requirejs optimiser) into a build folder, the baseUrl in the require.config is obviously now wrong.

baseUrl: 'js' points to public/js instead of public/build/js and so all paths are incorrect.

Is there a way of dynamically updating the baseUrl when running the optimiser? So it points to public/build/js?

Here's my grunt task:

requirejs: {
    dist: {
        options: {
            baseUrl: '<%=pkg.paths.js%>',
            dir:'project/public/build/js',
            mainConfigFile: '<%=pkg.paths.js%>main.js',
            optimize: 'none',
            removeCombined: true,
            uglify2: {
                no_mangle: true,
                compress: {
                    drop_console: true
                }
            },
            modules: [
                {
                    name: 'vendorCommon'
                },
                {
                    name: 'dashboard',
                    exclude: ['vendorCommon']
                }
            ]
        }
    }
}

Vendor Common

define(['jquery', 'foundation'],
function () {
    //Just an empty function, this is a place holder
    //module that will be optimized to include the
    //common depenendencies listed in this module's dependency array.
});

Require Config

require.config({

    baseUrl: '/js',

    priority: ['vendorCommon'],

    paths: {
        'vendorCommon':'vendor/vendor-common',
        'jquery':'../bower_components/jquery/dist/jquery.min',
        'foundation':'../bower_components/foundation/js/foundation/foundation',
        'dashboard':'views/dashboard'
    },

    shim: {
        'foundation': ['jquery']
    }

});
1

1 Answers

1
votes

I've used the optimizer's onBuildWrite setting to modify some modules when they are optimized. If your configuration is included in your optimized bundle then you could use onBuildWrite to patch it:

onBuildWrite: function (moduleName, path, contents) {
    if (moduleName === '<%=pkg.paths.js%>main') {
        return contents.replace("baseUrl: '/js'", "baseUrl: '/build/js'");
    }
    return contents;
}

Disclaimer: I'm writing this off the top of my head. Beware of typos.

Another possibility would be to override baseUrl at runtime. RequireJS is able to combine multiple configurations into a single configuration. A new value of baseUrl in a later call would override the earlier value. So if you have a way to set up the optimized version of your app (for instance, through different HTML served by your server) to call require.config({baseUrl: '/build/js'}); after the call you show in your question but before any code that needs the correct baseUrl, this could also be an option.