如何预编译 gulp-handlebars helpers?
How to precompile gulp-handlebars helpers?
我正在使用 gulp-handlebars 将我的模板预编译为 JS,但我无法让自定义 handlebars 助手也进行预编译。有谁知道是否有 support/way 预编译自定义辅助方法?
我注意到 gulp-handlebars 可以使用特定的 handlebars 库,基本上覆盖其默认值。因此,只需创建我自己的模块并注册一些助手,然后将其输入 handlebars 调用,事情就可以在本地进行。
// helpers.js
var handlebars = require('handlebars');
handlebars.registerHelper('upper', function(str){
return str.toUpperCase();
});
module.exports = handlebars;
然后在 gulp 文件中(像这样):
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 和可选的 watchify 并且需要输出为 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 文件,添加助手,然后导出该库。使用 gulp-defineModule 的 require 选项通过 helpers 传递 handlebars 库,如下所示:
.pipe(defineModule('node', {
require: {
Handlebars: '../helpers'
}
})
)
这将产生:
// template.js
var Handlebars = require("../helpers");
module.exports = Handlebars.template({...
请注意,相对路径将来自输出文件,并注意文件路径可能更改的 prod。
2: 另一种方法是使用 gulp-wrap 来精确定义模块。类似于:
.pipe(wrap('module.exports = function(Handlebars) {return Handlebars.template(<%= contents %>) }'))
然后在 main-js 中:
var Handlebars = require('./helpers');
var template = require('./template)(Handlebars);
我正在使用 gulp-handlebars 将我的模板预编译为 JS,但我无法让自定义 handlebars 助手也进行预编译。有谁知道是否有 support/way 预编译自定义辅助方法?
我注意到 gulp-handlebars 可以使用特定的 handlebars 库,基本上覆盖其默认值。因此,只需创建我自己的模块并注册一些助手,然后将其输入 handlebars 调用,事情就可以在本地进行。
// helpers.js
var handlebars = require('handlebars');
handlebars.registerHelper('upper', function(str){
return str.toUpperCase();
});
module.exports = handlebars;
然后在 gulp 文件中(像这样):
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 和可选的 watchify 并且需要输出为 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 文件,添加助手,然后导出该库。使用 gulp-defineModule 的 require 选项通过 helpers 传递 handlebars 库,如下所示:
.pipe(defineModule('node', {
require: {
Handlebars: '../helpers'
}
})
)
这将产生:
// template.js
var Handlebars = require("../helpers");
module.exports = Handlebars.template({...
请注意,相对路径将来自输出文件,并注意文件路径可能更改的 prod。
2: 另一种方法是使用 gulp-wrap 来精确定义模块。类似于:
.pipe(wrap('module.exports = function(Handlebars) {return Handlebars.template(<%= contents %>) }'))
然后在 main-js 中:
var Handlebars = require('./helpers');
var template = require('./template)(Handlebars);