Skip to content Skip to sidebar Skip to footer

How To Create Your Own Babel Processor Alternative To `react`

When you use JSX in a JS file, you have to import React or else the generated code won't compile. This is because this: import React from 'react' import ReactDOM from 'react-dom'

Solution 1:

The Babel plugin responsible for JSX processing is @babel/plugin-transform-react-jsx. Despite its React-specific name, you can use any pragma you like (React.createElement is the default pragma) by setting an option in your .babelrc file:

{
    "presets": ["@babel/preset-env"],
    "plugins": [
        ["@babel/plugin-transform-react-jsx", {
            "pragma": "MyThing.create"
        }]
    ]
}

In addition to pragma, there's pragmaFrag to set what the output should be for <>...</> JSX structures. (The default is React.Fragment.)

For example, Mithril.js uses "pragma": "m" and "pragmaFrag": "'['". Preact uses "pragma": "Preact.h" and "pragmaFrag": "Preact.Fragment".

~5 years ago I played with a different JSX-to-JavaScript compiler which worked quite well, but I can't find it now. Which makes sense: JavaScript has changed a lot in the last five years, and the time commitment to keep the compiler up-to-date with those changes would be non-trivial. It's easy to see a dev deciding not to pursue it given the success of Babel.

There is one alternative I know of: Sucrase. It only compiles JSX, TypeScript, and Flow, without Babel's plugin structure. (As a result, it's very fast.)

Post a Comment for "How To Create Your Own Babel Processor Alternative To `react`"