Handlebars.js and Webpack - precompile templates
10,523
You can use this handlebars loader for web pack https://github.com/pcardune/handlebars-loader/blob/master/README.md full info is given there but basically set the loader to compile all of your html files in your templates folder or rename them from .html to .hbs or .handlebars then simple require them in your modules and they will be compiled.
Author by
Frank
Updated on June 04, 2022Comments
-
Frank almost 2 years
I'm using
Backbone.js
,Handlebars.js
andWebpack
for my website. I used to useRequire.js
instead ofWebpack
. I have the following files:template.js
define({ structure: "structure.html", home: "home.html" });
webpack.config.js
resolve: { extensions: ['', '.js', '.json'], alias: { root: path.resolve( __dirname ), "router": path.resolve( __dirname ) + "/www/js/router", "templates": path.resolve( __dirname ) + "/www/js/templates", "handlebars": path.resolve( __dirname ) + "/node_modules/handlebars/dist/handlebars", "templates_html": path.resolve( __dirname ) + "/www/templates" } },
view.js
define( ['jquery', 'underscore', 'backbone', "utils" ], function($, _, Backbone, Utils) { var View = Utils.Page.extend({ constructorName: "View", id: "home", initialize: function() { this.template = Utils.templates.home; // this is what I need }, render: function () { this.$el.html( this.template( this.model.toJSON() ) ); return this; }, }); return View; });
I'd like to compile all templates with
Handlebars.js
at start of my website. When I was usingRequire.js
I was used to doing something like this:utils.js
define( ['jquery', 'underscore', 'backbone', 'handlebars', 'templates'], function($, _, Backbone, Handlebars, Templates) { var Utils = { templates: {} }; for (var t in Templates) { Templates[t] = "text!" + Templates[t]; } require(_.values(Templates), function() { var fragments = _.object(_.keys(Templates), arguments); // precompile all the fragments for (var t in fragments) { Utils.templates[t] = Handlebars.compile(fragments[t]); /* <Handlebars> */ } }); return Utils; });
How can I do something like that in utils.js with
webpack
?Thanks