babel-plugin-jsx-imports
babel-plugin-jsx-imports is a Babel plugin that automatically adds the necessary imports when a file contains JSX.
{
"plugins": [
"@babel/plugin-transform-react-jsx",
"babel-plugin-jsx-imports"
]
}
<>Hello World</>
/* becomes */
import React from "react"
React.createElement(React.Fragment, null, "Hello World")
babel-plugin-jsx-imports also lets you configure specific imports.
{
"plugins": [
["@babel/plugin-transform-react-jsx", {
"pragma": "createElement",
"pragmaFrag": "Fragment"
}],
["babel-plugin-jsx-imports", {
"pragma": "{ createElement } from react",
"pragmaFrag": "{ Fragment } from react"
}]
]
}
<>Hello World</>
/* becomes */
import { createElement, Fragment } from "react"
createElement(Fragment, null, "Hello World")
babel-plugin-jsx-imports also works well with Preact.
{
"plugins": [
["@babel/plugin-transform-react-jsx", {
"pragma": "h",
"pragmaFrag": "Fragment"
}],
["babel-plugin-jsx-imports", {
"pragma": "{ h } from preact",
"pragmaFrag": "{ Fragment } from preact"
}]
]
}
<>Hello World</>
/* becomes */
import { h, Fragment } from "preact"
h(Fragment, null, "Hello World")
Usage
Add babel-plugin-jsx-imports to your project:
npm install babel-plugin-jsx-imports --save-dev
Add babel-plugin-jsx-imports to your Babel configuration:
// babel.config.js
module.exports = {
plugins: [
'babel-plugin-jsx-imports'
]
}
Alternatively, configure transformations within your Babel configuration:
module.exports = {
plugins: [
['babel-plugin-jsx-imports', {
/* name the pragma import */
pragma: '{ createElement } from react',
/* name the pragma fragment import */
pragmaFrag: '{ Fragment } from react'
}]
]
}
Options
pragma
The pragma
option defines how the createElement
function is imported.
{
pragma: 'React from react',
pragma: '{ createElement } from react',
pragma: '{ createElement as h } from react'
}
pragmaFrag
The pragmaFrag
option defines how the Fragment
object is imported.
{
pragmaFrag: 'React from react',
pragmaFrag: '{ Fragment } from react',
pragmaFrag: '{ Fragment as F } from react'
}