How to use handlebars with webpacker

1k views Asked by At

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.

2

There are 2 answers

1
Francois On

after some experimenting I was able to get this working by changing my webpack/environment.js file to read as follows:

const { environment } = require('@rails/webpacker');
const path = require("path");
const webpack = require('webpack');

environment.plugins.set(
  'Provide',
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery'
  })
);

environment.loaders.set('Handlebars', {
  test: /\.hbs$/,
  use: {
    loader: 'handlebars-loader',
    query: {
      knownHelpersOnly: false,
      helperDirs: [
        path.resolve(__dirname, "../..", "app/javascript/handlebars-helpers")
      ]
    }
  }
});

module.exports = environment;

Now I am able to place handlebars helper methods in my app/javascript/handlebars-helpers directory and they get automatically picked up.

0
dixpac On

You should be able to get it working like this in the latest Rails version:

1.Add necessary dependencies

yarn add handlebars
yarn add handlebars-loader

2.Register your handlebars loader

 // config/webpack/loaders/handlebars.js
 module.exports = {
   test: /\.hbs$/,
   loader: 'handlebars-loader'
 }


 // config/webpack/environment.js  
 const { environment } = require('@rails/webpacker')
 const handlebars = require('./loaders/handlebars')

 environment.loaders.prepend('handlebars', handlebars)
 module.exports = environment

Rails Webpacker has pretty nice documentation about loaders, check it out here