2013-05-13 72 views
4

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

# 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) -> ... 

的,但似乎并没有工作。想法?

回答

2

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

基本上,如果如果它.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") 
+0

这有助于 - https://gist.github.com/luissquall/5408257 – imrane 2013-05-13 03:45:16

1

看看纸条,在计时器事件示例的底部:https://github.com/gruntjs/grunt-contrib-watch#using-the-watch-event

watch事件并非意在取代繁重的API。改为使用tasks

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

我只是想改变的文件...手表任务运行时编译在这些文件夹中的所有文件 – imrane 2013-05-13 02:27:38

+0

然后继续使用'grunt.config.set()'的'观看'事件。不要在'watch'事件中使用'grunt.task.run()'。这就是'任务'的目的。 – 2013-05-13 16:30:51

+0

我想在过滤出被更改的文件后运行该任务......那么我该怎么做? – imrane 2013-05-14 03:07:55