In my reactjs project, I am using handlebars to generate source code from the template. These templates are saved in files. In order to load these files into javascript, I configured below configuration in webpack
:
{
test: /\.handlebars|hbs$/,
loader:
'handlebars-loader?helperDirs[]=' +
path.join(__dirname, '../src/helpers/handlebars')
},
it works fine when I launch the production. But it doesn't work in my unit tests. I am using jest
as unit test framework. I have seen some people suggest to use Handlebars.registerHelper
. I know it works only for the template from string
. How to solve the issue when I load the template from files?
Getting started Next, install the Handlebars npm package, which contains the precompiler. Create a file name example. handlebars containing your template: Handlebars <b>{{doesWhat}}</b> precompiled!
Handlebars: What it is and Why to Use itHandlebars is a logic-less templating engine that dynamically generates your HTML page.
I created a preprocessor that simply put the handlebars template into a module so when imported in javascript via an es6 import, it can be used.
// preprocessor.js
module.exports = {
process(src) {
return `
const Handlebars = require('handlebars');
module.exports = \`${src}\`;
`;
},
};
Then in my package.json...
// package.json
"jest": {
"collectCoverage": true,
"modulePaths": [
"./app",
"./node_modules"
],
"testPathIgnorePatterns": [
"/node_modules/",
"/app/bower_components/"
],
"moduleFileExtensions": [
"js",
"hbs"
],
"transform": {
"\\.js$": "babel-jest",
"\\.hbs$": "<rootDir>/app/scripts/preprocessor.js"
}
}
In a src file...
import Mn from 'backbone.marionette';
import template from './template.hbs';
const ToggleList = Mn.CompositeView.extend({
template,
});
export default ToggleList;
When loading handlebar templates while testing with Jest, I found that the jest-handlebars package solved my problem.
From the docs:
npm i jest-handlebars --save-dev
To enable the processor please add the following rule to the transform object in your jest configuration:
"jest": { // ... transform: { "\\.hbs$": "jest-handlebars", } // ... }
Now all imported handlebars files will get compiled by the processor and the render function is imported.
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