如何将JSX文件转换为简单的JavaScript文件[离线转换] [英] How to convert react JSX files to simple JavaScript file [offline transformation]

查看:80
本文介绍了如何将JSX文件转换为简单的JavaScript文件[离线转换]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是react.js的新手。刚开始学习它。所以我的问题似乎很愚蠢,但请回答。

I am new to react.js. Just started learning it. So my question may seems to be stupid but please answer it.

我创建了一个简单的.js文件,其代码如下:

I have created a simple .js file with following code:

var Hello=React.createClass({
    render: function(){
        return (<h1>Hello World</h1>);
    }
});

它是JSX语法并将其转换为简单的JavaScript文件我使用以下命令:

It is in JSX syntax and to convert it to simple JavaScript file I used following command:

babel --preset react JSX_Files --watch --out-dir public/javascripts

这里 JSX_Files 是我的源文件夹, public / javascripts 是我想要转换的文件夹。 js文件。

Here JSX_Files is my source folder and public/javascripts is the folder where I want my transformed .js files.

但我在转换时遇到以下错误:

But I'm getting following error while transformation:

SyntaxError: JSX_Files/example.js: Unexpected token (3:16)
  1 | var Hello=React.createClass({
  2 |     render: function(){
> 3 |         return (<h1>Hello World</h1>);
    |                 ^
  4 |     }
  5 | });

但是当我使用Babel REPL时( http://babeljs.io/repl/ ),它会毫无错误地转换它。

But when I use Babel REPL (http://babeljs.io/repl/) , it converts it without any error.

现在请告诉我我做错了。为什么我在离线转换时遇到语法错误。

Now please tell me where I'm doing wrong. Why I'm getting syntax error while offline transformation.

推荐答案

如果您使用的是babel-cli,则需要使用插件来将jsx语法转换为浏览器理解的js语法。
请参阅以下链接:
http://babeljs.io / docs / plugins / transform-react-jsx /
您需要安装babel-plugin-transform-react-jsx插件并在.babelrc文件中使用它:

If you are using babel-cli you need to use a plugin to transform jsx syntax to js syntax that the browser understands. See the following link: http://babeljs.io/docs/plugins/transform-react-jsx/ You'll need to install babel-plugin-transform-react-jsx plugin and use it in a .babelrc file like that:

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

然后你的babel命令应该有效。

Then your babel command should work.

这篇关于如何将JSX文件转换为简单的JavaScript文件[离线转换]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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