I have a rails 5.1 app which makes use of the webpacker gem. My package.json file is as follows:
{
"dependencies": {
"@rails/webpacker": "^3.0.1",
"handlebars": "^4.0.10",
"handlebars-loader": "^1.6.0",
"jquery": "^3.2.1"
},
"devDependencies": {
"webpack-dev-server": "^2.7.1",
"webpack-merge": "^4.1.0"
}
}
And my webpack/environment.js file is as follows:
const { environment } = require('@rails/webpacker');
const webpack = require('webpack');
environment.plugins.set(
'Provide',
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
);
environment.loaders.set('Handlebars', {
test: /\.hbs$/,
use: 'handlebars-loader'
});
module.exports = environment;
if I create a foo.hbs file in app/javascript/templates then I can successfully compile that template using the following code:
const template = require("templates/foo.hbs");
const context = {name: "Fred", age: 5};
const html = template(context);
But the part that I'm having difficulty with is how to add handlebars helpers. I would like to have a folder app/javascript/handlebars-helpers and place helper functions in there but I'm unsure how to configure this. handlebars-loader has documentation that suggests how you can specify a helpers directory: https://github.com/pcardune/handlebars-loader/blob/master/examples/helperDirs/webpack.config.js but it isn't clear to me how I would add this to environment.js for webpacker.
after some experimenting I was able to get this working by changing my webpack/environment.js file to read as follows:
Now I am able to place handlebars helper methods in my app/javascript/handlebars-helpers directory and they get automatically picked up.