仅使用 Babel 转换 jsx

IT技术 javascript reactjs jsx babeljs
2021-05-27 06:00:33

我在 React js 中使用 Babel。问题是我不想将 es6 转换为 es5。我想继续使用es6。我只需要将 jsx 转换为 js。这是我的 .babelrc

{
  "plugins": ["transform-react-jsx"]
}

这是我的代码:

import React from "react";

/****** Header *******/
export class Header extends React.Component {
    onSubmit = (e) => {
        e.preventDefault();
        console.log('Submitting');
        const errors = this.validate();

        if (Object.keys(errors).length === 0) {
            this.setState({ loading: true });
            fetch(this.props.action, {
                method: 'POST',
                body: JSON.stringify(this.state.data),
                headers: new Headers({
                    'Content-Type': 'application/json'
                }),
                credentials: 'same-origin'
            }).then(res => res.json())
                .catch(error => console.error('Error:', error))
                .then(response => console.log('Success:', response));
        }
    };

    render() {
        return (
            <div>
                <a href={this.props.homeUrl}><img src={this.props.logoUrl} /></a>
                <div><span>Hello {this.props.userName}</span></div>
                <button onclick={this.onSubmit(e).bind(this)}>Click me</button>
            </div>
        );
    }
}

这是我在运行“babel components/Header.js -o Header.babel.js”时看到的

SyntaxError: components/Header.js: Unexpected token (5:13)
  3 | /****** Header *******/
  4 | export class Header extends React.Component {
> 5 |     onSubmit = (e) => {
    |              ^
  6 |         e.preventDefault();
  7 |         console.log('Submitting');
  8 |         const errors = this.validate();

它向我展示了 es6 代码行的语法错误 所以我认为 Babel 仍然需要将 es6 转换为 es5

安装“transform-class-properties”后,它显示另一条错误消息:

SyntaxError: components/Form.js: Unexpected token (55:12)
  53 |     getFieldValue(e) {
  54 |         this.setState({
> 55 |             ...this.state,
     |             ^
  56 |             data: {
  57 |                 ...this.state.data,
  58 |                 [e.target.name]: e.target.value

你知道有没有办法做到这一点?只将 JSX 转换为 JS

非常感谢你的支持

2个回答

您正在使用类属性语法,例如 someVar = () => {}

这不会被 jsx 插件转换。您需要为所有这些仍然是提案的高级功能添加插件。

这是用于类属性的 babel 插件:https : //babeljs.io/docs/plugins/transform-class-properties/

本质上,它只会转换你给它的插件,但浏览器还不支持类属性,更不用说在 node.js 中了。

如果该浏览器不支持所有 es6 功能或某些功能,则取决于您使用的浏览器,那么这些错误令人担忧