如何在 Grunt 中为不同的指南针任务组合多个 watch 任务

How to combine multiple watch tasks for different compass tasks in Grunt

我们在微调 Grunt 设置时遇到了一些问题。我们目前的项目设置是这样的。我们有一个 Themes 文件夹,在那个 themes 文件夹中有不同的主题,它们都有自己的 SCSS 文件和与该主题相关的其他位。

我们的 grunt 文件是这样设置的,大约有 15 个主题(省略了默认的 Grunt 设置和 JSHint,因为最终 Grunt 可以正常工作):

compass: {
    options: {
        ...
    }
    theme1: {
        src: ['App/Themes/theme1/scss/**/*.scss'],
        tasks: ['compass'],
        options: {
            sassDir: 'App/Themes/theme1/scss',
            cssDir: 'App/Themes/theme1'
        }
    },
    theme2: {
        src: ['App/Themes/theme2/scss/**/*.scss'],
        tasks: ['compass'],
        options: {
            sassDir: 'App/Themes/theme2/scss',
            cssDir: 'App/Themes/theme2'
        }
    },

    ...
}

concurrent: {
    watch: {
        tasks: ['compass:theme1', 'compass:theme2', ..., 'compass:themeXX'],
        options: {
            logConcurrentOutput: true,
            spawn: false
        }
    }
}

grunt.loadNpmTasks('grunt-concurrent');
grunt.loadNpmTasks('grunt-contrib-compass');
grunt.loadNpmTasks('grunt-contrib-watch');

grunt.registerTask('default', ['concurrent']);

实际的问题是,当我们启动默认任务时,也会启动 x 个监视线程。对于他们必须完成的小型监视任务,这有​​很多开销。

我正在寻找的解决方案是一种设置可以触发特定主题罗盘编译的单个监视任务的方法。有没有办法做到这一点?还是当前设置是唯一的方法?所以除了拥有 x 个监视任务之外别无选择?

谢谢。

首先,在监视文件但不执行任何任务的配置对象中构建一个监视任务。使用 glob 模式,告诉观察者监视主题目录中的所有 .scss 文件:

grunt.initConfig({
  compress: {}, //your existing compress object goes here
  watch: {
    themes: {
      files: ['App/Themes/**/*.scss'],
      tasks: []
    },
  },
});

接下来,您将向您的 g运行t 文件添加一个 grunt.event 侦听器。侦听器事件将公开已更改的文件(例如:App/Themes/theme1/scss/foobar.scss)。这样,您现在可以确定哪个压缩目标 (theme1) 到 运行:

grunt.event.on('watch', function(action, filepath, target) {
  if (target === 'themes') {
    var theme = filepath.split("/");
    grunt.task.run('compress.' + theme[2]); //tells grunt to run "compress.theme1" based on this example
  }
});