/handlebars-to-jsx

Converts Handlebars template to React component

Primary LanguageTypeScriptMIT LicenseMIT

Handlebars to JSX NPM Build Status

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

# via NPM
npm install handlebars-to-jsx

# or Yarn
yarn add handlebars-to-jsx

Usage

The package has only one method compile. You can import it by following way:

import { compile } from 'handlebars-to-jsx'

The method has following syntax:

compile(input[, options])
  • input
    The Handlebars template which should be converted to JSX code.
  • options Optional
    Options is an optional argument and can has the following properties:
    • isComponent Optional
      The default is true. Should return JSX code wrapped to a function component.
    • isModule Optional
      The default is false. Should return generated code exported by default.

Use it for simple converting Handlebars template to JSX code:

compile('<div>{{variable}}</div>')

// Result code
// props => <div>{props.variable}</div>

By default the compile function returns function component. You can convert Handlebars template to JSX without wrapping to arrow function. In this variant, props is not added to the path of variables.

compile('<div>{{variable}}</div>', { isComponent: false })

// Result
// <div>{variable}</div>

Also, you can get exported by default component:

compile('<div>{{variable}}</div>', { isModule: true })

// Result
// export default props => <div>{props.variable}</div>

Code formatting

The output code creates from AST tree, so it's unformatted by default. You can use tools like Prettier to format code:

import { compile } from 'handlebars-to-jsx'
import prettier from 'prettier'

// The Handlebars input
const hbsCode = '<div>{{#each list}}<span>{{item}}</span>{{/each}}</div>'

const jsxCode = compile(hbsCode, { isComponent: false })
// <div>{list.map((item, i) => <span key={i}>{item.item}</span>)}</div>;

prettier.format(jsxCode, { parser: 'babylon' })
// <div>
//   {list.map((item, i) => (
//     <span key={i}>{item.item}</span>
//   ))}
// </div>;

Transpilation

If you wanna have code of version JavaScript lower than ES6, or you wanna 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'

// The Handlebars input
const hbsCode = '<div>{{variable}}</div>'

const jsxCode = compile(hbsCode, { isComponent: false })
// <div>{variable}</div>;

const { code } = babel.transform(jsxCode, {
  plugins: [pluginTransformReactJSX]
})
// React.createElement("div", null, variable);

License

MIT licensed