1

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?

1 Answer 1

2

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
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this, that got me on the right track. And you're right, that documentation is not in the most evident place. I originally had tried r.optimize('build/app-main.js'); and that did not work at all so I'd given up, but after seeing your answer and knowing this is the right path, I dug into the r.js source a bit and saw it will accept a file if it's in an array. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.