How to use dynamic values in Grunt tasks called from inside a forEach?

丶灬走出姿态 提交于 2019-12-11 19:33:47

问题


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);
    });
});


来源:https://stackoverflow.com/questions/30931003/how-to-use-dynamic-values-in-grunt-tasks-called-from-inside-a-foreach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!