如何根据文件更改修改grunt watch任务?

ana*_*ism 5 node.js gruntjs compass-sass grunt-contrib-watch

我正在编写一个node.js程序,它将查看一个充满大量(300-s)数量的scss项目的目录.将配置Grunt-watch(通过节点模块或单独运行,无论运行什么),以便每当更改scss文件时,它将使用罗盘编译,输出文件移动到单独的目录,例如:

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

文件所在的项目目录显然非常重要(如果grunt-compass将所有已编译的文件发送到同一目录,它们将混乱且无法使用,并且grunt自动化将是无目的的).我命令确保所有文件都路由到正确的位置,每次更新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']);

  });

};
Run Code Online (Sandbox Code Playgroud)

但这不起作用.如果以详细模式运行'grunt watch',您将看到grunt在单独的进程中同时运行grunt.event.on函数和监视任务.gruntfile的第二次解析会恢复我的所有event.on配置更改为上面的默认值,并且指南针无法运行.

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

不幸的是,grunt.event.on变量没有被发送到定义的grunt-watch任务,否则我可以编写一个自定义函数来改变罗盘设置,然后在同一个过程中运行罗盘.

我已经尝试使用手表功能构建到指南针而没有咕噜声,但罗盘只能为每个项目存储一个静态输出路径,并且一次只能观看一个项目.

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

非常感谢您的任何见解.

go-*_*leg 11

你需要指定

options : { nospawn : true }

在您的监视任务配置中,让监视在相同的上下文中运行:

watch: {
  files: './*/*.scss',
  tasks: ['compass'],
  options : { nospawn : true }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 要添加此答案的更新,截至2016年6月,选项现在为:`spawn:false` (2认同)