繁体   English   中英

如何预编译gulp-handlebars助手?

[英]How to precompile gulp-handlebars helpers?

我正在使用gulp-handlebars将模板预编译到JS中,但是我无法让自定义的handlebars帮助程序也进行预编译。 有谁知道是否有任何支持/方法可以预编译自定义帮助方法?

我注意到gulp-handlebars可以使用特定的handlebars库,从本质上覆盖其默认库。 因此,只需创建我自己的模块并注册一些帮助程序,然后将其输入到handlebars调用中,就可以在本地工作。

// helpers.js
var handlebars  = require('handlebars');

handlebars.registerHelper('upper', function(str){
   return str.toUpperCase();
});

module.exports = handlebars;

然后在gulpfile中(类似这样):

var handlebars = require('./src/js/helpers.js');

gulp.task('handlebars', function(){
  gulp.src('src/html/*.html')
      .pipe(gulp_handlebars({handlebars: handlebars})) // override library here
});

如果您使用Browserify并选择性地进行观察,并且需要将输出作为commonjs样式模块,则gulp-defineModule将在已编译的模板文件中使用require('Handlebars')。 这将否定您已传递到gulp-handlebars自定义库选项中的所有注册帮助器(请参见上文)。 这是我们不需要的输出文件的示例:

// template.js
var Handlebars = require("handlebars");
module.exports = Handlebars.template({"compiler":[7,">= 4.0.0"]...

1:要解决此问题,请创建一个需要handlebars库的helpers.js文件,添加该helpers,然后导出该库。 使用gulp-defineModule的require选项可以通过如下的帮助器将其传递到把手库中:

.pipe(defineModule('node', {
        require: {
          Handlebars: '../helpers'
        }
      })
    )

这将产生:

// template.js
var Handlebars = require("../helpers");
module.exports = Handlebars.template({...

请注意,相对路径将来自outputfile,并在可能更改文件路径的产品上小心。

2:另一种方法是使用gulp-wrap精确定义模块的方式。 就像是:

.pipe(wrap('module.exports = function(Handlebars) {return Handlebars.template(<%= contents %>) }'))

然后在main-js中:

var Handlebars = require('./helpers');
var template = require('./template)(Handlebars);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM