Search code examples
node.jsrequirejsr.jsrequirejs-optimizer

Optimize multiple requirejs config file


I have a problem with optimization with r.js

I have a project that have multiple requirejs config file

+ app
    - module1    
        * main.js
        * foo.js
        * bar.js
    - main.js
+ build.js

that each main.js has self packages

main.js code is:

requirejs.config({
    'baseUrl': '../app/',
    'paths': {
        'module1' : 'module1/main'
    }
});
define(['module1'],function(){});

module1/main.js code like:

requirejs.config({
    'paths': {
        'foo' : 'module1/foo',
        'bar' : 'module1/bar'
    }
});
define(['foo','bar'],function(){});

and build.js file is like:

({
    mainConfigFile: 'app/main.js',
    baseUrl: 'app',
    name: 'main',
    out: 'dist/main.js',
})

when I execute $ r.js -o build.js it return an error

Tracing dependencies for: main
Error: ENOENT: no such file or directory, open 'D:\Project\Test\app\foo.js'
In module tree:
    main
      module1

Error: Error: ENOENT: no such file or directory, open 'D:\Project\Test\app\foo.js'
In module tree:
    main
      module1

    at Error (native)

Solution

  • To my knowledge, r.js is simply not able to process multiple requirejs.config calls when it builds a bundle. I've never seen any documentation or issue report, or working example that contradicts this. (RequireJS will let you call requirejs.config multiple times, and combine the configurations passed at run time but this is not the same as having r.js process multiple calls to requirejs.config.

    You'll have to combine all your calls to requirejs.config into a single call that you point r.js to with mainConfigFile.

    I've recreated your setup on my machine and got the same error you did. If I modify the config in app/main.js to the following, then I can build the bundle:

    requirejs.config({
        'baseUrl': '../app/',
        'paths': {
            'module1' : 'module1/main',
            'foo' : 'module1/foo',
            'bar' : 'module1/bar'
        }
    });
    

    Just for kicks, I've also tried the following which does not work:

    requirejs.config({
        'baseUrl': '../app/',
        'paths': {
            'module1' : 'module1/main'
        }
    });
    requirejs.config({
        'paths': {
            'foo' : 'module1/foo',
            'bar' : 'module1/bar'
        }
    });
    

    (Note also that baseUrl in the above could be simplified to . rather than ../app/.)