1.0.2 • Published 3 years ago

babel-jsx-pragma-module-auto-import v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

babel-jsx-pragma-module-auto-import

use jsx to create element and auto import the self define module by using self define babel pragma

Introduce

Plugin for babel 7+ to enable JSX for project, and it's a extension for @babel/preset-react to solve the problem module cannot auto import when using pragma.

@babel/preset-react has a pragma option that's used when transforming JSX to function calls instead of the default function React.createElement.

This Babel plugin is a companion to that feature that allows you to dynamically load a module associated with the pragma value.

Example:

Given this file:

const jsxComp = () => {
    return <div>anything</div>
}

export default jsxComp;

After use the plugin to auto import:

import { createElement } from "./lib";

const jsxComp = () => {
  return <div>anything</div>;
};

export default jsxComp;

How to install

npm i --save-dev babel-jsx-pragma-module-auto-import

How to use

Add the plugin to your package.json and update the plugin section in your .babelrc file. Or if your Babel settings are located inside the package.json - update the plugin section there.

It's important that you also include the babel-plugin-syntax-jsxplugin.

Example on a .babelrc file that will work:

Make sure plugin is added before babel module transformers

const path = require('path');
module.exports = {
    presets: [
        [
            '@babel/preset-react',
            {
                // 自定义createElement替代React.createElement
                pragma: 'createElement'
            }
        ],
        '@babel/preset-env'
    ],
    plugins: [
        [
            'module:babel-jsx-pragma-module-auto-import',
            {
                path: './lib',
                name: 'createElement'
            }
        ]
    ]
}