2013-07-29 30 views
5

我正在写一个node.js程序,它将观察一个充满大量(300海里)量的scss项目的目录。咕噜手表(运行或者通过节点模块或自己,无论作品)将被配置,使得每当SCSS文件被更改,将指南针编译,输出文件移动到一个单独的目录,例如:如何修改基于文件更改的grunt watch任务?

./1234/style.scss改变>>咕噜手表运行咕噜指南针>> /foo/bar/baz/1234/style.css更新

项目目录,该文件是明显非常重要(如果grunt-compass将所有编译后的文件发送到同一个目录,它们将会混乱且不可用,并且咕噜自动化将是无意义的)。我为了确保所有文件都被路由到正确的位置,我每次更新css文件时都会动态更改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的第二次解析会将我所有的event.on配置更改为上面的默认值,并且指南针无法运行。

正如在event.on注释中所看到的,我试图添加一个grunt.task.run()来确保指南针在与event.on函数相同的进程中运行,这将保留我的配置更改。但是该任务拒绝运行,可能是因为I'm doing it wrong

不幸的是,grunt.event.on变量不会发送到定义咕噜手表任务,否则我可以写将改变指南针设置,然后在同一个进程中运行罗盘的自定义函数。

我试过不咕噜实现这一点,使用手表功能建设成为指南针,罗盘但只能存储每个项目一个静态输出路径,只能看一个项目一次。

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

非常感谢你的任何见解。

+0

这不回答你的问题,但为什么会出现一个咕噜-的contrib手表的指南针?指南针已经自带了'指南针watch' – pllee

+0

你需要指定'选项:{nospawn:真正}'在你的手表任务配置有'在同样的情况下watch'运行([见文档本段](HTTPS:/ /github.com/gruntjs/grunt-contrib-watch#compiling-files-as-needed))。 –

+0

@ go-oleg谢谢!这很奇妙。我很惊讶,我没有在文档中看到它,因为它直接指出'nospawn'解决像我这样的问题。 – anachronism

回答

11

你需要在你的手表任务的配置指定

options : { nospawn : true }

有在同样的情况下手表运行:

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

它的更多信息,请参阅文件this section

+0

赞赏这个答案。已阅读文档,但不清楚“上下文”的含义以及它如何受'nospawn'选项的影响。谢谢! – jerome

+0

谢谢你的回答! – vgrinko

+2

要添加对此答案的更新,截至2016年6月,现在选项是:'spawn:false' – BigHeadCreations

相关问题