-->

How to use dynamic values in Grunt tasks called fr

2019-09-16 08:20发布

问题:

We are trying to run grunt tasks using grunt.config.set for dynamically concatinated strings. These grunt.configs are set in a forEach loop and change each time before the task is run.

This does unfortunately not work, as grunt only uses the last grunt.config.set and runs it multiple times with that very same value.

See this example with a simple "copy" task ("copy" is just an example, we want to use this kind of dynamic options in other tasks, too):

copy: {
    projectFiles : {
        files : [{
            src: 'src/<%= directoryName %>/*',
            dest: 'build/<%= directoryName %>/*'
        }]
    }
}   

grunt.registerTask('copyFiles', function() {
    var projects = ['directory1','directory2','directory3','directory4'];

    projects.forEach(function(project){
        grunt.config.set("directoryName", project);
        grunt.task.run('copy:projectFiles');
    });
});

This tasks copies four times src/directory4.

Is it somehow possible to build that kind of tasks which use dynamic values? It would be nice, as the only other solution would be to copy each task multiple times with static strings.

Thank you! Daniel

回答1:

The issue is that grunt.task.run does not run the task immediately, it just pushes it to the list of tasks to run later, while grunt.config.set executes immediately. So you end up with a list of 4 times the same task to execute.

You can get what you want by defining different targets dynamically, then running them, something like below:

grunt.registerTask('copyFiles', function() {
    var projects = ['directory1','directory2','directory3','directory4'];

    projects.forEach(function(project){
        grunt.config.set("copy." + project, {
            files : [{
                src: 'src/' + project + '/*',
                dest: 'build/' + project + '/'
            }]
        });
        grunt.task.run('copy:' + project);
    });
});