Would love to do the following in a backbone view file that will be "browserified" during a gulpjs build:
var template = require('../templates/pathToUncompiledTemplate');
The catch seems to be that this Handlebars file isn't compiled, thus not a JS file. The build works if I compile the template first to a tmp directory:
var template = require('../compiledtemplates/pathToACompiledTemplate');
With the promise of streaming builds and no more tmp files, I'm hoping someone more experienced with Browserify, Gulp, or both could point me in the right direction. To be very specific, the goal is to compile the templates during a gulp task, while still using require statements that reference the original template files, thus avoiding temp files. Possible?
You don't need to use Gulp for that. Just use browserify transform for compiling handlebars templates — browserify-handlebars.
% npm install browserify-handlebars
% browserify -t browserify-handlebars ./index.js
where index.js
and its dependencies can references Handlebars templates via using require(..)
:
var template = require('./template.handlebars');
var html = template({title: "An instantiated template!", name: "David"});
Note the .handlebars
extension — this what this particular transform looking for to be activated for any concrete file.
Of course you can invoke the same browserify setup from Gulp and thus have it integrated into your Gulp build pipeline, if you already have one. Otherwise I suggest you to stick with plain browserify, it's a powerful tool on its own.
An example of doing this with Gulp:
var gulp = require('gulp');
var browserify = require('gulp-browserify');
var browserifyHandlebars = require('browserify-handlebars');
gulp.task('scripts', function() {
// Single entry point to browserify
gulp.src('src/js/app.js')
.pipe(browserify({
transform: [browserifyHandlebars]
debug : !gulp.env.production
}))
.pipe(gulp.dest('./build/js'))
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With