如何将参数传递给grunt任务?

时间:2015-07-22 09:01:03

标签: gruntjs copy arguments task options

我想重构我的grunt复制任务,不要为多个子任务一遍又一遍地重复相同的文件。它现在看起来像这样:

    "copy":
    {
        "web-debug":
        {
            files:
            [
                { src: "libs/1st/**/*", dest: config.buildWebDebugOutPath },
                { src: "libs/3rd/**/*", dest: config.buildWebDebugOutPath },
                { src: "assets/**/*", dest: config.buildWebDebugOutPath },
                { src: "shared/**/*", dest: config.buildWebDebugOutPath },
                { src: "client/**/*", dest: config.buildWebDebugOutPath },
            ]
        },     
        "web-release":
        {
            files:
            [
                { src: "libs/1st/**/*", dest: config.buildWebReleaseOutPath },
                { src: "libs/3rd/**/*", dest: config.buildWebReleaseOutPath },
                { src: "assets/**/*", dest: config.buildWebReleaseOutPath },
                { src: "shared/**/*", dest: config.buildWebReleaseOutPath },
                { src: "client/**/*", dest: config.buildWebReleaseOutPath },
            ]
        },        

理想情况下,我只有一个复制任务,它接受一个路径参数,我可以从这样的别名任务传递给它:

//
// Let's assume I renamed "web-debug" to "web-files"
//
grunt.registerTask("web-debug", ["web-files:<some debug path>"]);
grunt.registerTask("web-release", ["web-files:<some release path>"]);

这样做最简单的方法是什么?

如何在任务本身中访问此传递的参数?

1 个答案:

答案 0 :(得分:2)

您可以使用模板,如此Dynamic Grunt Targets Using Templates博文中所述。在代码的上下文中,它可能如下所示:

"copy":
{
    "web-files":
    {
        files:
        [
            { src: "libs/1st/**/*", dest: "<%= grunt.task.current.args[0] %>" },
            { src: "libs/3rd/**/*", dest: "<%= grunt.task.current.args[0] %>" },
            { src: "assets/**/*", dest: "<%= grunt.task.current.args[0] %>" },
            { src: "shared/**/*", dest: "<%= grunt.task.current.args[0] %>" },
            { src: "client/**/*", dest: "<%= grunt.task.current.args[0] %>" },
        ]
    }

您可以传入完整路径或只传入部分&#34;调试&#34;或&#34;发布&#34;路径段。