使用Gulpjs编译客户端Jade模板

Cai*_*tti 4 javascript templates gulp pug

我正在尝试将所有.jade模板编译成单个js文件,我正在使用Gulpjs和gulp-jade,gulp-concat ..

我可以获得单个文件,但问题是所有呈现的函数都具有相同的名称,它们都被称为"模板".

foo.jade:

.fooDiv
    h1 Foo here
Run Code Online (Sandbox Code Playgroud)

foo2.jade:

.foo2Div
    h1 Foo2 here
Run Code Online (Sandbox Code Playgroud)

Gulp文件:

gulp.src("templates/**/*.jade")
    .pipe(jade({client: true}))
    .pipe(concat("templates.js"))
    .pipe(gulp.dest("../website/templates"))
Run Code Online (Sandbox Code Playgroud)

那将输出这样的文件:

function template(locals) {
    var buf = [];
    var jade_mixins = {};

    buf.push("<div class=\"fooDiv\"><h1>Foo here</h1></div>");;return buf.join("");
}
function template(locals) {
    var buf = [];
    var jade_mixins = {};

    buf.push("<div class=\"foo2Div\"><h1>Foo2 here</h1></div>");;return buf.join("");
}
Run Code Online (Sandbox Code Playgroud)

而我想要的是:

function foo(locals) {
    var buf = [];
    var jade_mixins = {};

    buf.push("<div class=\"fooDiv\"><h1>Foo here</h1></div>");;return buf.join("");
}
function foo2(locals) {
    var buf = [];
    var jade_mixins = {};

    buf.push("<div class=\"foo2Div\"><h1>Foo2 here</h1></div>");;return buf.join("");
}
Run Code Online (Sandbox Code Playgroud)

有什么方法可以做到这一点吗?我一直在寻找相当长的一段时间,但没有找到任何东西.

干杯.卡欧

编辑:

Jade现在接受jade.compileClient的name选项.在这里查看:https://github.com/jadejs/jade/blob/master/jade.js

Shu*_*awa 8

它似乎是jade.compileClient硬编码function template(locals),它没有更改功能名称的选项.https://github.com/visionmedia/jade/blob/master/lib/jade.js

这有点hacky但你可以在jade编译后修改编译脚本的内容.

var through = require('through2');
var path = require('path');

function modify() {
  function transform(file, enc, callback) {
    if (!file.isBuffer()) {
      this.push(file);
      callback();
      return;
    }
    var funcName = path.basename(file.path, '.js');
    var from = 'function template(locals) {';
    var to = 'function ' + funcName + '(locals) {';
    var contents = file.contents.toString().replace(from, to);
    file.contents = new Buffer(contents);
    this.push(file);
    callback();
  }
  return through.obj(transform);
}

gulp.src("templates/**/*.jade")
    .pipe(jade({client: true}))
    .pipe(modify())
    .pipe(concat("templates.js"))
    .pipe(gulp.dest("../website/templates"));
Run Code Online (Sandbox Code Playgroud)

如果您的jade模板位于多个子目录中,您可以funcName根据需要更改file.path.