我有两个目录src
和compiled
,我想使用Grunt Watch来确保从src
到compiled
的单向数据同步。作为中间步骤,我还想编译*.less
文件以及一些使用ES6语法编写的*.js
文件子集。
我已成功编写了所需任务:
// NOTE: Spawn must be disabled to keep watch running under same context in order to dynamically modify config file.
watch: {
// Compile LESS files to 'compiled' directory.
less: {
options: {
interrupt: true,
spawn: false,
cwd: 'src/less'
},
files: ['**/*.less'],
tasks: ['less']
},
// Copy all non-ES6/LESS files to 'compiled' directory. Include main files because they're not ES6. Exclude LESS because they're compiled.
copyUncompiled: {
options: {
event: ['added', 'changed'],
spawn: false,
cwd: 'src'
},
files: ['**/*', '!**/background/**', '!**/common/**', '!contentScript/youTubePlayer/**/*', '!**/foreground/**', '!**/test/**', '!**/less/**', '**/main.js'],
tasks: ['copy:compileSingle']
},
// Compile and copy ES6 files to 'compiled' directory. Exclude main files because they're not ES6.
copyCompiled: {
options: {
event: ['added', 'changed'],
spawn: false,
cwd: 'src/js'
},
files: ['background/**/*', 'common/**/*', 'contentScript/youTubePlayer/**/*', 'foreground/**/*', 'test/**/*', '!**/main.js'],
tasks: ['babel:compileSingle']
},
// Whenever a file is deleted from 'src' ensure it is also deleted from 'compiled'
remove: {
options: {
event: ['deleted'],
spawn: false,
cwd: 'src'
},
files: ['**/*'],
tasks: ['clean:compiledFile']
}
}
grunt.event.on('watch', function(action, filepath, target) {
// Determine which task config to modify based on the event action.
var taskTarget = '';
if (action === 'deleted') {
taskTarget = 'clean.compiledFile';
} else if (action === 'changed' || action === 'added') {
if (target === 'copyCompiled') {
taskTarget = 'babel.compileSingle';
} else if (target === 'copyUncompiled') {
taskTarget = 'copy.compileSingle';
}
}
if (taskTarget === '') {
console.error('Unable to determine taskTarget for: ', action, filepath, target);
} else {
// Drop src off of filepath to properly rely on 'cwd' task configuration.
grunt.config(taskTarget + '.src', filepath.replace('src\\', ''));
}
});
这些任务监视相应的文件。事件处理程序动态修改clean
copy
和babel
任务,使它们适用于被添加 / 更改 / 删除的文件。
然而,我正在观察数千个文件,观察任务需要非常长的时间来初始化。在我的高端开发电脑上初始化需要6秒以上的时间。这个问题恶化了事实,观察任务在每个任务之后都会重新初始化。
这意味着如果我有两个文件fileA
和fileB
,我修改fileA
并保存,那么将有一个6秒以上的时间段,其中观察无法检测到对fileB
的修改。这导致我的两个目录之间出现不同步。
我在GitHub上找到了与我的问题相关的问题,但它仍然未解决:https://github.com/gruntjs/grunt-contrib-watch/issues/443
Github 上的讨论指出当spawn: false
已设置时可能会出现此问题,但是根据 Grunt Watch 文档:
如果需要动态修改配置,则必须禁用 spawn 选项,以使观察在同一上下文中运行。
因此,我认为我需要继续使用spawn: false
。
我必须假定这是 Grunt 任务的一个相当标准的过程。我是否忽略了显而易见的事情?Watch 任务是否不适合此目的?其他选择?