Grunt命令行参数

时间:2013-11-21 17:13:33

标签: gruntjs

我有一个Grunt构建文件。我的构建文件有一个如下所示的任务:

myTask: {
  options: {
    configFile: "config/default.js",
    args: {   }
  },
  dev: {
    configFile: 'config/local.js',
    options: { args: {} },
  },
  test: {
    configFile: 'config/remote.js',
    options: { args: {} }
  }
}

...

grunt.registerTask('customTask', ['myTask:dev']);
grunt.registerTask('customTask-Test', ['myTask:test']);

目前,我可以从命令行运行以下命令:

> grunt customTask

一切正常。但是,我需要添加这样的能力:

> grunt customTask --myParam=myValue

我需要在我的" dev"中查看myParam的值。任务目标。但是,我无法弄清楚如何做到这一点。 如果我可以在myTask:dev运行时打印出myParam的值,我会很高兴。换一种说法, 我希望在运行时看到以下内容

> grunt customTask

> grunt customTask --myParam=hello
You entered hello

> grunt customTask-Test

> grunt customTask-Test --myParam=hello

我该怎么办?

4 个答案:

答案 0 :(得分:37)

grunt.option页面对此进行了解释。

在您的情况下,您可以使用以下内容获取myParam的值

var target = grunt.option('myParam');

答案 1 :(得分:4)

我做了一个使用示例,我可以通过这个命令行传递我希望我的css.min创建的模块:

> grunt cssmin --target=my_module 

Gruntfile.js

module.exports = function(grunt) {    
 var module = grunt.option('target'); //get value of target, my_module
 var cssminPath = 'assets/' + module + '/css/all.css';

 grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    cssmin:{
        css: {
            files: [{
                    src: [
                        'bower_components/bootstrap/dist/css/bootstrap.min.css',
                    ],
                    dest: cssminPath
                }]
        }
    },
  });
  grunt.loadNpmTasks('grunt-contrib-cssmin');
  grunt.registerTask('default', ['cssmin']);
}

答案 2 :(得分:3)

另一种方法:您可以使用process.argv数组,就像在常规节点应用中一样。

GruntJS当然是基于NodeJS构建的。

我使用这种技术将我的Grunt命令行参数转发到我的Node进程,由grunt-nodemon调用。

答案 3 :(得分:2)

您还可以使用process.argv数组读取来自grunt的命令行args

var args = process.argv;
runScript(args[2], args[3]);

第一个&第二个参数是node命令和脚本名称。

execute: {
    target: {
      options: {
         args : [arg1, arg2]
      },
      src: ['script.js']
    }
}

使用grunt-execute

相关问题