簡體   English   中英

僅使用 Babel 轉換 jsx

[英]Use Babel to transform jsx only

我在 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

非常感謝你的支持

您正在使用類屬性語法,例如someVar = () => {}

這不會被 jsx 插件轉換。 您需要為所有這些仍然是提案的高級功能添加插件。

這是用於類屬性的 babel 插件: https : //babeljs.io/docs/plugins/transform-class-properties/

本質上,它只會轉換你給它的插件,但瀏覽器還不支持類屬性,更不用說在 node.js 中了。

如果該瀏覽器不支持所有 es6 功能或某些功能,則取決於您使用的瀏覽器,那么這些錯誤令人擔憂

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM