使用Babel进行React应用转译jsx [英] Transpiling jsx using babel for react app

查看:399
本文介绍了使用Babel进行React应用转译jsx的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用babel转换jsx文件并给出错误消息.

I am trying to transpile a jsx file using babel and its giving an error.

文件内容如下(src/app.js)

class Channel extends React.Component{
    render() {
        return(
            <li> Something </li>
        )
    }
}

我使用以下命令来转译并查看文件中的更改.

I used the following commands to transpile and watch the file for changes.

1) babel src/app.js --watch --out-file js/app.js
2) babel src/app.js --presets es2015 --watch --out-file js/app.js

在两种情况下,我都收到以下错误消息,

In both the cases I recieved the following error,

SyntaxError: src/app.js: Unexpected token (4:12)
  2 |     render() {
  3 |         return(
> 4 |             <li> Something </li>
    |             ^
  5 |         )
  6 |     }
  7 | }

它表明错误是在javascript文件(jsx)中嵌入的html标签的开头.希望Babel知道html标记并对其进行处理和编译,但是我不知道为什么它会那样表现.

It shows that the error is at the start of the html tags embedded in the javascript file (jsx). Babel is expected to know the html tags and treat it and compile it, but I don't know why does it behave like that.

注意:我使用官方网站上的babel文档安装了babel.

Note: I installed babel using the babel documentation from the official website.

推荐答案

您还需要react预设.

要安装它:

npm i babel-preset-react

要使用它:

babel src/app.js --presets es2015,react --watch --out-file js/app.js

这篇关于使用Babel进行React应用转译jsx的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆