javascriptrequirejsjasminegrunt-contrib-requirejs

RequireJS optimiser not loading paths from external config?


I'm using r.js through grunt-contrib-requirejs and haven't had any problems with it so far, until I wanted to split up my config into a separate file so that both testem and my app could share the same config. I haven't got any problems with having the separate config, except when it comes to the optimiser which can't find the paths any more.

My main file loads in require like so:

<script data-main="main" src="vendor/requirejs/require.js"></script>

In main.js I have:

require(['config'], function() {
    'use strict';
    require(['backbone', 'jquery'], function( Backbone, $ ) {
        // ...
    });
});

And in the config I have:

require.config({
    paths : {
        backbone                : 'vendor/backbone/backbone-min',
        jquery                  : 'vendor/jquery/jquery.min',
        underscore              : 'vendor/underscore/underscore-min'
    },
    shim : {
        'backbone'              : { deps: ['jquery', 'underscore'], exports: 'Backbone' },
        'underscore'            : { exports: '_' }
    }
});

My Grunt task looks like this:

compile : {
    options: {
        name: 'main',
        baseUrl: 'lib',
        mainConfigFile: 'lib/config.js',
        out: 'dist/js/master.js',
        optimizeAllPluginResources: true
    }
}

But all r.js can find is lib/config.js & lib/main.js, it doesn't find Backbone, jQuery etc. This all works OK if config is included in the same file as main, but the whole point of splitting these out is so that I don't have to maintain a different config for my test runner.

Any advice would be greatly appreciated.


Solution

  • Managed to solve this a couple of days ago. Now using Almond to load in my optimised r.js build and so I use a config like this:

    compile: {
        options: {
            name: 'vendor/almond/almond',
            baseUrl: 'lib',
            include: ['main'],
            insertRequire: ['main'],
            mainConfigFile: 'lib/config.js',
            out: 'dist/js/master.js',
            optimizeAllPluginResources: true,
            wrap: true
        }
    }
    

    For the development version I had to include the config inside a different script below where I inserted require.js:

    <script src="config.js"></script>
    

    But for the optimiser I had to load config as a module: e.g.

    require(['backbone','jquery','config'], function( Backbone, $ ) {
    

    I couldn't get nested requires to work, so this is the solution that I came up with. Posting this for future Googlers.