Grunt:观察文件更改并编译父目录

我正在使用grunt来处理一个项目,我之前没有使用过grunt,现在已经设置为监视文件,当文件已被更改时,使用handleb将所有文件(包含数百个文件的多个子目录)重新编译为html这很慢。 我想通过编译需要的东西来提高速度。

用grunt newer来看文件并不是真正的工作,因为目录中有依赖关系,因此只有重新编译已更改的文件才会生成有效的页面。

我基本上需要重新编译已经改变的文件的整个父目录,但我不太确定如何configuration这样的东西。

任何提示,我应该看看?

汇编本身是这样configuration的:

var _ = require('lodash'); var path = require('path'); // expand the data files and loop over each filepath var pages = _.flatten(_.map(grunt.file.expand('./src/**/*.json'), function(filepath) { // read in the data file var data = grunt.file.readJSON(filepath); var dest=path.dirname(filepath)+ '/' +path.basename(filepath, path.extname(filepath)); dest=dest.replace("src/",""); var hbs; if (data.hbs){ hbs=grunt.file.read(path.dirname(filepath)+ '/' + data.hbs) } // create a 'page' object to add to the 'pages' collection return { // the filename will determine how the page is named later filename: dest, // the data from the json file data: data, // add the recipe template as the page content content:hbs }; })); return { options: { /*postprocess: require('pretty'),*/ marked: {sanitize: false}, data: '<%= options.src %>/**/*.json', helpers: '<%= options.src %>/helpers/helper-*.js', layoutdir: '<%= options.src %>/templates', partials: ['<%= options.src %>/components/**/*.hbs'] }, build: { options: { layout: 'base.hbs', assets: '<%= options.build %>', pages: pages }, files: [ { cwd: '<%= options.src %>', dest: '<%= options.build %>', src: '!*' } ] }, } 

所以每次加载所有的页面都像/src/sites/abc/xyz/foo.json一样被扫描下来,然后进行编译,但是我只想修改文件。 Watch确实检测到已更改的文件,但是所有文件都被重新编译,我不知道如何才能将configuration中已识别的已更改的文件只处理部分文件。

我觉得你需要的东西已经在那里了。

在grunt文档中检查使用watch事件 。

在这里复制内容以满足SO MODS/GODS

当观看的文件被修改时,该任务将发出观看事件。 如果您希望在编辑文件时使用简单通知,或者如果您正在使用此任务与其他任务一起使用,则此function非常有用。 这是一个使用watch事件的简单例子:

 grunt.initConfig({ watch: { scripts: { files: ['lib/*.js'], }, }, }); grunt.event.on('watch', function(action, filepath, target) { grunt.log.writeln(target + ': ' + filepath + ' has ' + action); }); 

监视事件不是为了replaceconfiguration和运行任务的标准Grunt API。 如果你试图从watch事件中运行任务,你很可能做错了。 请阅读configuration任务。

根据需要编译文件

一个非常常见的要求是只根据需要编译文件。 下面是一个仅使用jshint任务来更改文件的示例:

 grunt.initConfig({ watch: { scripts: { files: ['lib/*.js'], tasks: ['jshint'], options: { spawn: false, }, }, }, jshint: { all: { src: ['lib/*.js'], }, }, }); // on watch events configure jshint:all to only run on changed file grunt.event.on('watch', function(action, filepath) { grunt.config('jshint.all.src', filepath); }); 

如果您需要dynamic修改configuration,则必须禁用spawn选项以使手表在相同的上下文中运行。

如果你同时保存多个文件,你可以select一个更强大的方法:

 var changedFiles = Object.create(null); var onChange = grunt.util._.debounce(function() { grunt.config('jshint.all.src', Object.keys(changedFiles)); changedFiles = Object.create(null); }, 200); grunt.event.on('watch', function(action, filepath) { changedFiles[filepath] = action; onChange(); });