Home Ask Login Register

Developers Planet

Your answer is one click away!

Djave February 2016

How to compile JSX with Babel into JavaScript

I'm trying to compile the very simplest React tutorial using browserify. I've run:

sudo npm install browserify

Then as stated here http://babeljs.io/docs/setup/#browserify

sudo npm install --save-dev babelify

Then I have my file js/script.jsx

var HelloMessage = React.createClass({
  render: function() {
    return <div>Hello {this.props.name}</div>;

ReactDOM.render(<HelloMessage name="John" />, mountNode);

And I'm running from the folder

browserify js/script.jsx -t babelify --outfile bundle.js

But then this happens:

djave at djaves-iMac-3 in /Volumes/djave/react
$ browserify js/script.jsx -t babelify --outfile bundle.js
SyntaxError: /Volumes/djave/react/js/script.jsx: Unexpected token (4:11)
  2 | var HelloMessage = React.createClass({
  3 |   render: function() {
> 4 |     return <div>Hello {this.props.name}</div>;
    |            ^
  5 |   }
  6 | });
  7 | 

What am I doing wrong? This is literally my first step into this area so it may be I've missed a pretty major step.

More errors (although I suspect this won't help too much!)

 at Parser.pp.raise (/Volumes/djave/react/node_modules/babelify/node_modules/babel-core/node_modules/babylon/index.js:1425:13)
 at Parser.pp.unexpected (/Volumes/djave/react/node_modules/babelify/node_modules/babel-core/node_modules/babylon/index.js:2907:8)
 at Parser.pp.parseExprAtom (/Volumes/djave/react/node_modules/babelify/node_modules/babel-core/node_modules/babylon/index.js:754:12)
 at Parser.pp.parseExprSubscripts (/Volumes/djave/react/node_modules/babelify/node_modules/babel-core/node_modules/babylon/index.js:509:19)
 at Parser.pp.parseMaybeUnary (/Volumes/djave/react/node_modules/babelify/node_modules/        


Djave February 2016

All fixed, thanks to @azium.

First get the React preset: http://babeljs.io/docs/plugins/preset-react/

npm install babel-preset-react

Next, create a file called .babelrc in the root of your project, and put in it the following:

  "presets": ["react"]

Then do the

browserify js/script.jsx -t babelify --outfile bundle.js

That compiles everything, and as an extra to make sure that react and react-dom are included (as shown here) you can run the following:

sudo npm install --save react react-dom 

Post Status

Asked in February 2016
Viewed 3,839 times
Voted 4
Answered 1 times


Leave an answer

Quote of the day: live life