18

grunt タスクをカスタマイズするには、grunt の起動時にコマンド ラインで指定された grunt タスク名にアクセスする必要があります。

十分に文書化されているため、オプションは問題ありません(grunt.options)。また、 grunt task を実行するときにタスク名を見つける方法についても十分に文書化されています。

しかし、前にタスク名にアクセスする必要があります。

たとえば、ユーザーは次のように書きます grunt build --target=client

で grunt ジョブを構成するときにGruntfile.js、 を使用 grunt.option('target')して を取得できます'client'

buildしかし、タスクのビルドが開始される前にパラメータを取得するにはどうすればよいですか?

どんなガイダンスも大歓迎です!

4

3 に答える 3

3

grunt.task.currentプロパティを含む、現在実行中のタスクに関する情報を持つ whichを使用することをお勧めしnameます。タスク内では、コンテキスト (つまりthis) は同じオブジェクトです。そう 。. .

grunt.registerTask('foo', 'Foobar all the things', function() {
  console.log(grunt.task.current.name); // foo
  console.log(this.name); // foo
  console.log(this === grunt.task.current); // true
});

buildが他のタスクのエイリアスであり、現在のタスクを実行するために入力されたコマンドを知りたいだけの場合、通常は を使用しますprocess.argv[2]。を調べると、 is (はプロセスであるため)、is 、およびis が実際の単調なタスクprocess.argvであることがわかります (その後に の残りのパラメーターが続きます)。argv[0]nodegruntnodeargv[1]gruntargv[2]argv

編集:

タスク内console.log(grunt.task.current)からのgrunt@0.4.5からの出力例(現在のタスク以外からの現在のタスクを持つことはできません)。

{
  nameArgs: 'server:dev',
  name: 'server',
  args: [],
  flags: {},
  async: [Function],
  errorCount: [Getter],
  requires: [Function],
  requiresConfig: [Function],
  options: [Function],
  target: 'dev',
  data: { options: { debugPort: 5858, cwd: 'server' } },
  files: [],
  filesSrc: [Getter]
}
于 2015-01-31T22:29:49.927 に答える
1

これに使えますgrunt.util.hooker.hook

例 (Gruntfile.coffee の一部):

grunt.util.hooker.hook grunt.task, (opt) ->
  if grunt.task.current and grunt.task.current.nameArgs
    console.log "Task to run: " + grunt.task.current.nameArgs

コマンド:

C:\some_dir>grunt concat --cmp my_cmp
Task to run: concat
Running "concat:coffee" (concat) task
Task to run: concat:coffee
File "core.coffee" created.

Done, without errors.

特定のタスクの実行を防ぐために使用したハックもあります。

grunt.util.hooker.hook grunt.task, (opt) ->
  if grunt.task.current and grunt.task.current.nameArgs
    console.log "Task to run: " + grunt.task.current.nameArgs
    if grunt.task.current.nameArgs is "<some task you don't want user to run>"
      console.log "Ooooh, not <doing smth> today :("
      exit()  # Not valid. Don't know how to exit :), but will stop grunt anyway

CMD、許可されている場合:

C:\some_dir>grunt concat:coffee --cmp my_cmp
Running "concat:coffee" (concat) task
Task to run: concat:coffee
File "core.coffee" created.

Done, without errors.

CMD、防止された場合:

C:\some_dir>grunt concat:coffee --cmp my_cmp
Running "concat:coffee" (concat) task
Task to run: concat:coffee
Ooooh, not concating today :(
Warning: exit is not defined Use --force to continue.

Aborted due to warnings.
于 2013-06-14T14:20:39.170 に答える