简体   繁体   中英

How to precompile gulp-handlebars helpers?

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?

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
});

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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