babel-plugin-jsx-imports

1.0.0 • Public • Published

babel-plugin-jsx-imports Babel

NPM Version Build Status Support Chat

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'
}

Package Sidebar

Install

npm i babel-plugin-jsx-imports

Weekly Downloads

67

Version

1.0.0

License

CC0-1.0

Unpacked Size

41.2 kB

Total Files

8

Last publish

Collaborators

  • jonathantneal