如何使用Grunt有条件地编译只更改了模板引入的jade文件

8

在这里使用 grunt-contrib-watch 推荐的编译仅更改的文件版本:https://github.com/gruntjs/grunt-contrib-watch#compiling-files-as-needed

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();
});

这个(有一个我写的变体在这里可以正常工作:https://gist.github.com/pgilad/6897875

问题在于使用Jade模板中的include,也就是说你需要包含其他Jade模板以构建完整的HTML文件。

使用编译的单一解决方案无法解决问题,因为如果你正在处理的.jade文件是通过include current_working_jade.jade嵌入的,那么包含的文件将不会被重新编译。

除了从头开始编译所有jade文件之外,是否有任何解决方法?当你需要编译大约60个大型jade文件时,这会导致问题。

我唯一能想到的解决方案是映射Jade模板的依赖项,可以使用外部或目录,但我不知道有哪些工具/插件可以做到这一点...

2个回答

4

在我开始开发一个将生成一种jade sourcemap的脚手架时,我发现了这个已经解决了这个问题的伟大项目:

Jade Inheritance

使用方法如下:

  1. 使用以下命令安装包:npm install jade-inheritance --save-dev
  2. 想要从jade中获取依赖文件列表的位置:

    var JadeInheritance = require('jade-inheritance');

    var inheritance = new JadeInheritance(file, basedirname, {basedir:basedirname});

  3. 然后当你想要获取文件时:

    depenedentFiles = inheritance.files;

  4. 该项目还演示了如何通过 grunt.watch 应用概念,以便仅编译与它们的依赖项不同的 jade 文件,这正是我所需要的:

使用jade-inheritance和grunt watch


这个能用于多文件夹、继承文件吗?我们在调试时无法设置,希望能得到您的帮助 :) - Ajay Patel

1
我想象一下,就像检查所有的jade文件,如果它们包含了你更改的文件,那么也重新编译。应该不难。伪代码如下:
var allFiles = getAllJadeFileWithIncludesAndProjectPathMap();
//allFiles now contains something like this

{
  'jade/index.jade': ['jade/menu.jade', 'jade/home.jade'],
  'jade/about.jade': ['jade/menu.jade']
}


var rootFiles = [];

_.each(allFiles, function (includes, parent) {
  _.each(includes, function (includePath) {
    var parent;
    while (parent = getParentPath(includePath)) {
      //nothing needed if getParentPath returns null for files that aren't included
    }

    if (rootFiles.indexOf(parent) !== -1) {
      rootFiles.push(parent);
    }
  });
});

现在将这些文件添加到编译任务中。

嗯,getAllJadeFileWithIncludesAndProjectPathMap() 函数正是我在寻找的。所以基本上,在获取到 changed 事件后 - 我会在 Array 中找到它并编译 jade 及其所有子级... 不仅如此,我还在寻找一个已经存在的解决方案,而不想自己重新发明轮子。 - Gilad Peleg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接