How to precompile gulp-handlebars helpers?

流过昼夜 提交于 2019-12-11 10:26:43

问题


I am precompiling my templates into JS using gulp-handlebars but I am having trouble getting custom handlebars helpers to also precompile. Does anyone know if there is any support/way to precompile custom helper methods?


回答1:


I noticed that gulp-handlebars can use a specific handlebars library, essentially overriding its default. So, by just creating my own module and registering some helpers, and feeding that into the handlebars call, things are working locally.

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

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

module.exports = handlebars;

And then in the gulpfile (something like this):

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

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



回答2:


If you're using Browserify and optionally watchify and need the output to be a commonjs style module, gulp-defineModule will use a require('Handlebars') in the compiled template file. This negates any registered helpers that you had passed into gulp-handlebars custom library option (see above). Here is an example of the output file we don't want:

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

1: To fix this, create a helpers.js file that requires the handlebars library, adds the helpers, and then exports the library. Use gulp-defineModule's require option to pass in the handlebars library with the helpers like so:

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

this will produce:

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

Note that the relative path will be from the outputfile, and be careful on prod where filepaths may change.

2: Another way is to use gulp-wrap to define the module exactly how you want it. Something like:

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

then in main-js:

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


来源:https://stackoverflow.com/questions/33491782/how-to-precompile-gulp-handlebars-helpers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!