问题
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