gianthead
gianthead

Reputation: 1

How to pass arguments to grunt task?

I want to refactor my grunt copy task to not repeat the same files over and over for multiple sub tasks. It looks like this right now:

    "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 },
            ]
        },        

Ideally, I just have one copy task that takes a path argument that I can pass to it from an alias task like this:

//
// 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>"]);

What's the simplest way of doing this?

How would I access this passed in argument within the task itself?

Upvotes: 0

Views: 987

Answers (1)

James
James

Reputation: 11931

You can use templates, as described in this Dynamic Grunt Targets Using Templates blog post. In the context of your code, it might look like this:

"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] %>" },
        ]
    }

You could pass in either the full path or just a partial "debug" or "release" path segment.

Upvotes: 2

Related Questions