监视grunt-contrib-watch的子任务

Monitoring sub-task for grunt-contrib-watch

本文关键字:子任务 grunt-contrib-watch 监视      更新时间:2023-09-26

我有下面的Gruntfile.coffee。我正在监视如下所示的watch任务,以查看文件更改,然后将更改后的文件编译为coffee-script。

# Watch task
watch:
 coffee:
  files: ['client/**/*.coffee','server/**/*/.coffee']
  options:
   nospawn: true
   livereload: true
# Watch changed files
grunt.event.on 'watch', (action, filepath) ->
 cwd = 'client/'
 filepath = filepath.replace(cwd,'')
 grunt.config.set('coffee',
  changed:
   expand: true
   cwd: cwd
   src: filepath
   dest: 'client-dist/'
   ext: '.js'
 )
 grunt.task.run('coffee:changed')

然而,我想添加另一个监视任务来复制非咖啡文件的文件。我该如何监控这些变化?

我想做

# Watch copy task
grunt.event.on 'watch:copy', (action,filepath) -> ...
# Watch coffee task
grunt.event.on 'watch:coffee', (action,filepath) -> ...

但这似乎不起作用。想法吗?

我的解决方案-完成工作,但不是很漂亮。我欢迎更好的答案

基本上,我匹配传入文件
的路径如果是。coffee,运行coffee编译任务
如果是。*运行拷贝任务
# Watch changed files
grunt.event.on 'watch', (action, filepath) ->
 # Determine server or client folder
 path = if filepath.indexOf('client') isnt -1 then 'client' else 'server'
 cwd = "#{path}/"
 filepath = filepath.replace(cwd,'')        
 # Minimatch for coffee files
 if minimatch filepath, '**/*.coffee'
  # Compile changed file
  grunt.config.set('coffee',
   changed:
    expand: true
    cwd: cwd
    src: filepath
    dest: "#{path}-dist/"
    ext: '.js'
  )
  grunt.task.run('coffee:changed')  
 # Minimatch for all others
 if minimatch filepath, '**/*.!(coffee)'
  # Copy changed file
  grunt.config.set('copy',
   changed:
    files: [
     expand: true
     cwd: cwd
     src: filepath
     dest: "#{path}-dist/"                      
    ]
  )
  grunt.task.run("copy:changed")

看一下手表事件示例底部的注释:https://github.com/gruntjs/grunt-contrib-watch#using-the-watch-event

watch事件并不打算替换Grunt API。使用tasks代替:

watch:
  options:
    nospawn: true
    livereload: true
  coffee:
    files: ['client/**/*.coffee','server/**/*/.coffee']
    tasks: ['coffee']
  copy:
    files: ['copyfiles/*']
    tasks: ['copy']