Cameron
Cameron

Reputation: 2296

r.js from node script?

I feel like this must be so obvious but it's escaping me.

I'd like to run requirejs's r.js compilation from a node module instead of from the command line, and every bit of documentation I've seen just shows the command line option. Something like this is what I'm looking for:

var r = require('requirejs');
r('./build/common.js');
r('./build/app-main.js');

Let me explain the underlying motivation in case there's a better way to do it:

I've got a few different build.js files that I want to run r.js on (separate bundles for common dependencies and the main app). I'd like to wrap this up inside a gulpfile or gruntfile that runs both, and without putting all the r.js config in the actual grunt/gulp file like the grunt and gulp require.js plugins all seem to do. Leaving the r.js config in the separate build/*.js files would let us use grunt/gulp OR command line when we want to.

Any way to accomplish this?

Upvotes: 1

Views: 1436

Answers (1)

Louis
Louis

Reputation: 151391

Using the optimizer as a Node module is documented but it is not in the most evident place. This is the example that the documentation gives:

var requirejs = require('requirejs');

var config = {
    baseUrl: '../appDir/scripts',
    name: 'main',
    out: '../build/main-built.js'
};

requirejs.optimize(config, function (buildResponse) {
    //buildResponse is just a text output of the modules
    //included. Load the built file for the contents.
    //Use config.out to get the optimized file contents.
    var contents = fs.readFileSync(config.out, 'utf8');
}, function(err) {
    //optimization err callback
});

Upvotes: 2

Related Questions