我有同样的问题。我使用regarde:file
事件解决了它。
首先,我使用regarde:file
事件监听更改的文件。这将为两个任务提供配置:clean:coffee
源位置中的文件是否已删除以及coffee:refresh
文件是否已更改/添加。
然后该regarde
任务将触发其任务,该任务将启动refresh:coffee
(不要误会coffee:refresh
)。此任务将检查是否为clean:coffee
和/或添加了配置,coffee:refresh
并在需要时运行这些任务(通过函数 grunt.task.run
)。如果还会重置标志,这将导致下一个接收到regarde:file
的事件再次清理配置。
深入解释:
首先,regarde
配置:
// watch for changed coffeescript files
coffee: {
files: 'path/to/coffee/**/*.coffee',
tasks: ['refresh:coffee', 'livereload']
},
然后我监听该regarde:file
事件,并在其配置中更新clean:coffee
和coffee:refresh
文件列表。
根据regarde:file
事件提供配置:
grunt.event.on('regarde:file', function (status, target, filepath) {
if (resetFlag) {
// clean file list from previous cycle, so clean clean:coffee and coffee:refresh
// file lists
...
resetFlag = false;
}
if (status === 'deleted') {
if (filepath) {
// calculate filepath's destination and
// add it to clean:coffee filelist
}
} else {
if (!grunt.file.isDir(filepath)) {
// add filepath to coffee:refresh filelist
}
}
}
grunt.config()
通过函数更新配置很容易。在要馈送的代码片段下方coffee:refresh
和clean:coffee
.
将配置添加到coffee:refresh
:
var config = grunt.config('coffee') || {};
var value = config.refresh || {};
value.files = value.files || [];
...
var cwd = path.dirname(filepath),
src = path.basename(filepath),
dest = cwd.replace('path/to/source', 'path/to/dest');
value.files.push({
expand:true,
src:src,
dest:dest,
cwd:cwd,
ext:'.js'
});
grunt.config('coffee', config);
将配置添加到clean:coffee
:
var cwd = path.dirname(filepath),
src = path.basename(filepath),
dest = cwd.replace('path/to/source', 'path/to/dest');
value.src.push(path.join(dest, src.replace('coffee', 'js')));
// clean only what has been removed
config = grunt.config('clean') || {};
config.coffee = value;
grunt.config('clean', config);
任务refresh:coffee
被触发:
grunt.registerMultiTask('refresh', 'refreshing the changed file(s)', function () {
this.requires('regarde');
var tasks = [];
var clean = grunt.config('clean');
// check if there is clean:refresh config available
if (clean && clean[this.target]) {
tasks.push('clean:' + this.target);
}
var config = grunt.config(this.target);
// check if there is coffee:refresh config available
if (config && config.refresh) {
tasks.push(this.target + ':refresh');
}
// run the tasks
grunt.task.run(tasks);
// set the resetFlag back to true
resetFlag = true;
});