gruntjsrequirejsgrunt-contrib-requirejs

GruntJS and custom task: require a RequireJS module


I am quite new with GruntJS and I wonder if it is possible to have a task that loads some RequireJs modules to process them and write the result within a JS file.

I describe my scenario:

I have a RequireJs based project with many files. I would like to concatenate/minify/etc the project to deploy it and increase performances, etc.

The optimization works perfectly with the grunt-contrib-requirejs plugin. The grunt-contrib-requirejs plugin works with a main.js file and I should need to generate it dynamically.

I would like to generate the main.js processing some RequireJS module of the project (call them fileA.js and fileB.js). I would like to use the generated main.js to run the grunt-contrib-requirejs plugin.

So the task sequence would be something like:

Custom Task:

  1. loads fileA.js and fileB.js
  2. merge them together
  3. write the result of the merging within a new JS file

grunt-contrib-requirejs task:

  1. use the generated main.js file to optimize the project

Do you know how can I achieve this? I don't have any kind of restrictions on the way/tools/libs to use.


Solution

  • You can load RequireJS in Grunt, as follows:

    var requirejs = require('requirejs');

    You can then fetch all the fileX.js files in your tree through Grunt:

    grunt.file.recurse('js/modules/', function callback(abspath, rootdir, subdir, filename) {
        if (filename === 'fileX.js') {
          /* Do something here. */  
        }
    }

    Once you have all the modules you need you can use r.js to minify/concatenate them.