Search code examples
reactjsbrowserifybabeljs

Unexpected token with react jsx and babel


I was trying to get started with react. I installed npm, browserify, babel and its presets. Babel not able to transform JSX code. Can anyone help me understand what is happening. Am i using the correct presets for babel ? My demo.js

"use strict";

var React = require('react');
var ReactDOM = require('react-dom');

var Test = React.createClass({
    render: function(){
        var {a, b, ...other} = this.props;
        return(
            <div>Hi</div>
        );
    }
});

This is the command i run to create bundle.

sudo browserify -t [ babelify --presets [ es2015 react ] ] src/demo.js -o ./bundle/app.js

Following is the error i get

SyntaxError: /Users/shashank/git_views/srh_labs/webui/src/demo.js: Unexpected token (8:13)
   6 | var Test = React.createClass({
   7 |  render: function(){
>  8 |      var {a, b, ...other} = this.props;
     |              ^
   9 |      return(
  10 |          <div>Hi</div>
  11 |      );
    at Parser.pp.raise (/Users/shashank/git_views/srh_labs/webui/node_modules/babylon/lib/parser/location.js:24:13)
    at Parser.pp.unexpected (/Users/shashank/git_views/srh_labs/webui/node_modules/babylon/lib/parser/util.js:91:8)
    at Parser.pp.parseIdentifier (/Users/shashank/git_views/srh_labs/webui/node_modules/babylon/lib/parser/expression.js:999:10)
    at Parser.pp.parsePropertyName (/Users/shashank/git_views/srh_labs/webui/node_modules/babylon/lib/parser/expression.js:821:135)
    at Parser.pp.parseObj (/Users/shashank/git_views/srh_labs/webui/node_modules/babylon/lib/parser/expression.js:737:12)
    at Parser.pp.parseBindingAtom (/Users/shashank/git_views/srh_labs/webui/node_modules/babylon/lib/parser/lval.js:163:19)
    at Parser.pp.parseVarHead (/Users/shashank/git_views/srh_labs/webui/node_modules/babylon/lib/parser/statement.js:591:18)
    at Parser.<anonymous> (/Users/shashank/git_views/srh_labs/webui/node_modules/babylon/lib/plugins/flow.js:953:13)
    at Parser.parseVarHead (/Users/shashank/git_views/srh_labs/webui/node_modules/babylon/lib/plugins/flow.js:953:13)
    at Parser.pp.parseVar (/Users/shashank/git_views/srh_labs/webui/node_modules/babylon/lib/parser/statement.js:574:10)
$ sudo browserify -t [ babelify --presets [ es2015 react ] ] src/demo.js -o ../server/rest/src/main/webapp/uiserver/bundle/app.js 

Solution

  • The object rest/spread operator (used on line 8) is not part of the es2015 package. You have to install the transform-object-rest-spread plugin to transform that.