Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic mapping for destinations in grunt.js

Tags:

gruntjs

I have a project with several sub folders that contain JavaScript files I want to concatenate. what would be the right way to configure them?

eg.

source: /modules/$modulename/js/*.js (several files) dest: /modules/$modulename/js/compiled.js

So what I want to do is to compile js-files of an unknown/unconfigured count of subfolders ($modulename) into one file per subfolder.

Is this possible?


The following function (built after hereandnow78's instructions) does the job:

grunt.registerTask('preparemodulejs', 'iterates over all module directories and compiles modules js files', function() {

    // read all subdirectories from your modules folder
    grunt.file.expand('./modules/*').forEach(function(dir){

        // get the current concat config
        var concat = grunt.config.get('concat') || {};

        // set the config for this modulename-directory
        concat[dir] = {
            src: [dir + '/js/*.js', '!' + dir + '/js/compiled.js'],
            dest: dir + '/js/compiled.js'
        };

        // save the new concat config
        grunt.config.set('concat', concat);

    });

});

after that i put preparemodulejs before the concat job in my default configuration.

like image 709
Patrick Avatar asked Jun 09 '13 13:06

Patrick


1 Answers

you will probably need to code your own task, where you iterate over your subfolders, and dynamically append to your concat configuration.

grunt.registerTask("your-task-name", "your description", function() {

  // read all subdirectories from your modules folder
  grunt.file.expand("./modules/*").forEach(function (dir) {

    // get the current concat config
    var concat = grunt.config.get('concat') || {};

    // set the config for this modulename-directory
    concat[dir] = {
     src: ['/modules/' + dir + '/js/*.js', '!/modules/' + dir + '/js/compiled.js'],
     dest: '/modules/' + dir + '/js/compiled.js'
    };

    // save the new concat configuration
    grunt.config.set('concat', concat);
  });
  // when finished run the concatinations
  grunt.task.run('concat');
});

run this with:

$ grunt your-task-name

this code is untested, but i think it should do your job.

HINT: you can put this code into an external file and include in your gruntfile if you want to keep your gruntfile small, e.g. put this into a file inside a tasks-directory:

module.exports = function(grunt) {
  grunt.registerTask("your-task-name", "your description", function() {
    ...
  });
};

and load in in your gruntfile:

grunt.loadTasks("./tasks");
like image 62
hereandnow78 Avatar answered Oct 17 '22 00:10

hereandnow78