How to convert react JSX files to simple JavaScript file [offline transformation]

耗尽温柔 提交于 2019-12-08 07:08:42

问题


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

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

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

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

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 | });

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.


回答1:


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"]
}

Then your babel command should work.




回答2:


Try babel --presets react JSX_Files --watch --out-dir public/javascripts (s on the end of preset).



来源:https://stackoverflow.com/questions/34456182/how-to-convert-react-jsx-files-to-simple-javascript-file-offline-transformation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!