如何修改基于文件更改的grunt watch任务?

我正在编写一个node.js程序,它将监视一个充满大量(300小时)的scss项目的目录。 Grunt-watch(无论是通过节点模块运行还是独立运行,无论哪种方式运行)都将被configuration,以便每当scss文件发生更改时,都会使用指南针进行编译,输出文件将移至单独的目录,例如:

./1234/style.scss已更改>> grunt-watch运行grunt-compass >> /foo/bar/baz/1234/style.css更新

该文件所在的项目目录显然是非常重要的(如果grunt-compass将所有已编译的文件发送到同一个目录,那么它们就会变得混乱而不可用,而且这个混乱的自动化将是无意义的)。 我为了确保所有的文件被路由到正确的地方,我每次更新css文件时都会dynamic地改变grunt-compass设置。

示例gruntfile:

module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), watch: { files: './*/*.scss', tasks: ['compass'] }, compass: { origin:{ options: { //temportary settings to be changed later sassDir: './', cssDir: './bar', specify: './foo.scss' } } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-compass'); grunt.event.on('watch', function(action, filepath, target) { var path = require('path'); grunt.log.writeln(target + ': ' + filepath + ' might have ' + action); var siteDirectory = path.dirname(filepath); //changes sass directory to that of the changed file var option = 'compass.origin.options.sassDir'; var result = __dirname + '/' + siteDirectory; grunt.log.writeln(option + ' changed to ' + result); grunt.config(option, result); //customizes css output directory so that file goes to correct place option = 'compass.origin.options.cssDir'; result = path.resolve(__dirname, '../', siteDirectory); grunt.log.writeln(option + ' changed to ' + result); grunt.config(option, result); //grunt.task.run(['compass']); }); }; 

但是这不起作用。 如果在详细模式下运行“grunt watch”,您将看到grunt在不同的进程中运行grunt.event.on函数和watch任务。 gruntfile的第二个parsing会将所有的event.onconfiguration更改为上面的默认值,而指南针无法运行。

正如在event.on中所看到的,我试图添加一个grunt.task.run()来确保指南针与event.on函数在同一个进程中运行,这将保留我的configuration更改。 然而,这个任务拒绝运行,可能是因为我做错了 。

不幸的是,grunt.event.onvariables不会被发送到定义的grunt-watch任务,否则我可以编写一个自定义函数来改变指南针的设置,然后在同一个进程中运行指南针。

我已经尝试过实现这个没有咕噜声,使用手表function构build到指南针,但指南针只能存储一个静态输出path,每个项目,只能看一个项目一次。

我目前通过添加一个节点程序来解决这个问题,该程序将站点名称作为参数,通过使用fs运行来重写grunfile.js,然后通过exec函数运行“grunt watch”。 然而,这有它自己的缺点(我不能查看grunt.log数据),是可怕的复杂,所以我想改变它。

非常感谢您的任何见解。

你需要指定

options : { nospawn : true }

在您的手表任务configuration中让手表在相同的上下文中运行:

 watch: { files: './*/*.scss', tasks: ['compass'], options : { nospawn : true } } 

有关详细信息,请参阅此部分的文档。