Handlebars to JSX
Converts Handlebars template to JSX-component. Uses Glimmer VM to parse Handlebars code to AST and Babel to create JSX AST and generate code.
Installation
npm install handlebars-to-jsx
yarn add handlebars-to-jsx
Usage
The package only has one method compile
. You can import it the following way:
import { compile } from 'handlebars-to-jsx'
The method has the following syntax:
compile(input[, options])
input
The Handlebars template which should be converted to JSX code.options
Optional
Options is optional and can have the following properties:
isComponent
Optional
The default is true
. Should return JSX code wrapped as a function component.isModule
Optional
The default is false
. Should return generated code exported as default.includeImport
Optional
The default is false
. Should return generated code with React import at the top. Requires isModule
to be true.
Use it for simply converting Handlebars template to JSX code:
compile('<div>{{variable}}</div>')
By default the compile
function returns a function component. You can convert Handlebars templates to JSX without wrapping them as arrow functions. In this variant, props
is not added to the path of variables.
compile('<div>{{variable}}</div>', { isComponent: false })
Also, you can have the component exported as default:
compile('<div>{{variable}}</div>', { isModule: true })
Also, react can be imported:
compile('<div>{{variable}}</div>', { includeImport: true, isModule: true })
Code formatting
The output code is created from an AST tree, so it's unformatted by default. You can use tools like Prettier to format the code:
import { compile } from 'handlebars-to-jsx'
import prettier from 'prettier'
const hbsCode = '<div>{{#each list}}<span>{{item}}</span>{{/each}}</div>'
const jsxCode = compile(hbsCode, { isComponent: false })
prettier.format(jsxCode, { parser: 'babylon' })
Transpilation
If you want to have code lower than ES6, or you want to have the React source JS code without JSX, you can use babel:
import { compile } from 'handlebars-to-jsx'
import babel from '@babel/core'
import pluginTransformReactJSX from '@babel/plugin-transform-react-jsx'
const hbsCode = '<div>{{variable}}</div>'
const jsxCode = compile(hbsCode, { isComponent: false })
const { code } = babel.transform(jsxCode, {
plugins: [pluginTransformReactJSX]
})
License
MIT licensed