Grunt Command Line Parameters

跟風遠走 提交于 2019-12-18 18:41:22

问题


I have a Grunt build file. My build file has a task that looks like the following:

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']);

Currently, I can run the following from the command line:

> grunt customTask

Everything works fine. However, I need to add the ability to do something like this:

> grunt customTask --myParam=myValue

I need to look at the value of myParam in my "dev" task target. However, I can't figure out how to do it. I would be happy if I could just print out the value of myParam when myTask:dev is ran. In other words, I'd like to see the following when run

> grunt customTask

> grunt customTask --myParam=hello
You entered hello

> grunt customTask-Test

> grunt customTask-Test --myParam=hello

How do I do something like this?


回答1:


This is all explained in the grunt.option page.

In your case, you could get the value of myParam with:

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



回答2:


I made an example of use, where i can pass the module where i want my css.min to be created through this command line:

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



回答3:


An alternate way: you can use the process.argv array, just like you can in a regular Node app.

GruntJS is, of course, built on NodeJS.

I used this technique in order to forward my Grunt command-line args to my Node process, called by grunt-nodemon.




回答4:


You can also use the process.argv array te read the command line args from grunt

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

the first & second arguments are the node command and the script name.

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

using grunt-execute



来源:https://stackoverflow.com/questions/20127586/grunt-command-line-parameters

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