GruntJS, Multiple Tasks and grunt.option

I am starting to use GruntJS for one of my projects. I have easily accomplished to write a simple build script using simple aliases.

However my script contains many tasks that are basically the same, the only difference are some parameters like the source folder and destination folder.

For example:

    sass: {
        options:{
            trace: true,
            debugInfo: true,
            style: 'compressed'
        },
        html: {
            files: {
                'build/html/css/main.css': 'sass/html.sass'
            }
        },
        html2: {
            files: {
                'build/html2/css/main.css': 'sass/html2.sass'
            }
        },
        html3: {
            files: {
                'build/html3/css/main.css': 'sass/html3.sass'
            }
        }
    }

What I would like to achieve is to have only one task and then pass parameters (dest,src) to that task.

I tried to implement this using MultiTasks:

grunt.registerTask('sass2', 'Run all Sass compilation tasks.', function() {
    var projects = ['html','html2','html3'];

    projects.forEach(function(proj){
        grunt.config.set('sass.files.dest', 'build/' + proj + '/css/main.css');
        grunt.config.set('sass.files.src', 'sass/' + proj + '.sass');
        grunt.log.writeln(grunt.config.get('sass.files.dest'));
        grunt.log.writeln(grunt.config.get('sass.files.src'));
        grunt.task.run('sass');

    });
});

Grunt log outputs the right values for the params, however only the html3 sass gets compiled.

I do not understand why only one of the projects gets compiled and how could I fix this.

Perhaps there is another way to solve this problem. A better way. Maybe using templates?

Any kind of help or tips would be appreciated.

Thank you!

Only the last configuration is used because grunt.task.run queues them to run after the current task is complete. From the API:

Enqueue one or more tasks. Every specified task in taskList will be run immediately after the current task completes, in the order specified

What you have is:

  • Set config 1
  • Set config 2
  • Set config 3
  • Run three tasks using the currently active config, which is #3.

Instead, you can do something like this to dynamically create lots of config sections and then run those tasks:

grunt.config.set('sass.' + proj + '.files', [{
    src: 'sass/' + proj + '.sass',
    dest: 'build/' + proj + '/css/main.css'
}]);

and then call runtask with your newly-created section:

grunt.task.run('sass:' + proj);