[英]Precompile handlebars templates into seperate JST (.js) files with Gulp
[英]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.