动态Grunt Watch配置

时间:2014-10-27 14:53:02

标签: javascript css gruntjs grunt-contrib-watch grunt-contrib-less

我的网站文件结构是这样的:

app
    less
        themes
            default
            modern
            etc
public
    themes
        default
            css
        modern
            css
        etc

因此/app/less/themes/{{ themeName }}/*.less将汇编为/public/themes/{{ themeName }}/css/*.css

我的Grunt Less任务动态设置并且工作正常。 示例:grunt less:compileTheme:modern

less: {
  compileTheme: {
    options: {
      compress: false,
      yuicompress: false,
      optimization: 2,
      sourceMap: true,
      sourceMapFilename: "public/themes/<%= grunt.task.current.args[0] %>/css/styles.css.map",
      sourceMapURL: "/themes/<%= grunt.task.current.args[0] %>/css/styles.css.map"
    },
    files: {
      "public/themes/<%= grunt.task.current.args[0] %>/css/styles.css": "app/less/themes/<%= grunt.task.current.args[0] %>/styles.less"
    }
  }
}

但我不确定如何让Grunt Watch任务正常运作。理想情况下,它会看到主题文件夹名称并以grunt less:compileTheme:{{ themeName }}运行grunt任务:

watch: {
    themeCss: {
        files: "app/less/themes/{{ themeName }}/**/*.less",
        tasks: ["less:compileTheme:{{ themeName }}"],
        options: {
          spawn: false
        }
    }
}

这可能吗?和/或有更好的方法我应该这样做吗?

1 个答案:

答案 0 :(得分:1)

编辑您的监视任务以运行less:compileTheme - 没有themeName的任务,并在您的主题文件夹中查看所有较少的文件:

watch: {
    themeCss: {
        files: "app/less/themes/**/*.less",
        tasks: ["less:compileTheme"],
        options: {
          spawn: false
        }
    }
}

现在您可以添加一个监视事件处理程序来获取更改的文件。提取themeName,并配置你的less-task:

grunt.event.on('watch', function(action, filepath) {
  var themeName = filepath.split('/')[3];
  grunt.config('less.compileTheme.files', {
    "public/themes/" + themeName + "/css/styles.css": "app/less/themes/" + themeName + "/styles.less"
  });
});

当然,你的themeName的检测应该更可靠,但我认为你可以了解如何进行动态观看!