如何将babel转译的代码转换成正常的js

o8x7eapl  于 2023-09-28  发布在  Babel
关注(0)|答案(1)|浏览(132)

我正在使用一个名为babel-plugin-transform-react-class-to-function的插件,用于将react类转换为功能组件。它是将给定的输入转换成转译的Babel代码,但我希望在给定插件的github的自述文件中指定的原始纯代码。我该怎么做>
例:给定输入enter image description here
提供的输出。enter image description here
需输出

import PropTypes from 'prop-types';
import { Component } from 'react';

export const HelloWorld = ({ className }) => <div className={className}>Hello world!</div>;

HelloWorld.propTypes = {
  className: PropTypes.string,
};
huus2vyu

huus2vyu1#

你需要一个额外的Babel插件:

  • @babel/plugin-syntax-jsx - parse JSX syntax

例如
babel.config.json

{
  "plugins": [
    "@babel/plugin-syntax-jsx",
    "babel-plugin-transform-react-class-to-function"
  ]
}

于:
index.jsx

import PropTypes from 'prop-types';
import React, { Component } from 'react';

export class HelloWorld extends Component {
    static propTypes = {
        className: PropTypes.string,
    };

    render() {
        const { className } = this.props;

        return <div className={className}>Hello world!</div>;
    }
}

编译命令:

npx babel ./index.jsx -d ./

输出:

import PropTypes from 'prop-types';
import React, { Component } from 'react';
const HelloWorld = ({
  className
}) => {
  return <div className={className}>Hello world!</div>;
};
HelloWorld.propTypes = {
  className: PropTypes.string
};
export { HelloWorld };

软件包版本:

"react": "^18.2.0",
"react-dom": "^18.2.0",
"@babel/cli": "^7.22.15",
"@babel/core": "^7.22.17",
"@babel/plugin-syntax-jsx": "^7.22.5",
"babel-plugin-transform-react-class-to-function": "^1.2.2",
"prop-types": "^15.8.1"

相关问题