如何使用 grunt 目标

how to use grunt target

我的 Gruntfile.js 是这样的:

 'use strict';

module.exports = function(grunt) {
    grunt.initConfig({
        grunt.config.set('targ', grunt.option('target'));
        cachebuster: {
            build: {
                options: {
                    basedir: 'WebContent',
                    formatter: function(hashes) {
                        var json = {};
                        for (var filename in hashes) {
                            json["/" + filename] = hashes[filename];
                        }
                        return JSON.stringify(json);
                    }
                },
                src: [ 'WebContent/assets/**/*.js', 'WebContent/assets/**/*.css' ],
                dest: 'src/main/resources/cachebusters.json'
            }
        }
    });

// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-cachebuster');    

// Default task.
grunt.registerTask('default', ['cachebuster']);

};

我想根据 dev 或 deploy 命令行参数更改 dest 的位置..

即如果命令行 arg 是 dev 那么 dest:'cachebuster.json' 如果命令行 arg 已部署,则 dest:'src/main/resources/cachebuster.json'

我如何实现这个?

您可以尝试以下代码块。默认情况下,如果您不提供任何参数,第一个目标将被执行(在本例中为 dev):

cachebuster: {
  dev: {
    options: {
      basedir: 'WebContent',
      formatter: function(hashes) {
        var json = {};
        for (var filename in hashes) {
          json["/" + filename] = hashes[filename];
        }
        return JSON.stringify(json);
      }
    },
    src: ['WebContent/assets/**/*.js', 'WebContent/assets/**/*.css'],
    dest: 'src/main/resources/cachebusters.json'
  },
  deploy: {
    options: {
      basedir: 'WebContent',
      formatter: function(hashes) {
        var json = {};
        for (var filename in hashes) {
          json["/" + filename] = hashes[filename];
        }
        return JSON.stringify(json);
      }
    },
    src: ['WebContent/assets/**/*.js', 'WebContent/assets/**/*.css'],
    dest: 'src/main/resources/cachebusters.json'
  }
}

如果您想跨目标共享选项,请使用以下代码块。

cachebuster: {
  options: {
    basedir: 'WebContent',
    formatter: function(hashes) {
      var json = {};
      for (var filename in hashes) {
        json["/" + filename] = hashes[filename];
      }
      return JSON.stringify(json);
    }
  },
  dev: {
    src: ['WebContent/assets/**/*.js', 'WebContent/assets/**/*.css'],
    dest: 'src/main/resources/cachebusters.json'
  },
  deploy: {
    src: ['WebContent/assets/**/*.js', 'WebContent/assets/**/*.css'],
    dest: 'src/main/resources/cachebusters.json'
  }
}