2013-05-13 74 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