Parse error when running grunt-browserify on a React component

1.3k Views Asked by At

I'm just toying around with React and have a basic setup using grunt and grunt-browserify, but I'm getting a parse error. Anyone know a solution for this? Side note - the task runs fine when I don't use react/jsx.

With a basic component:

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

React.render(<HelloWorld />, document.getElementById('app'));

I get this error:

>> File "assets/javascripts/app.js" changed.
Running "browserify:dist" (browserify) task
>> /Users/username/www/reactor/assets/javascripts/app.js:4
>>       <div>
>>       ^
>> ParseError: Unexpected token
Warning: Error running grunt-browserify. Use --force to continue.

And here is the grunt task:

  browserify: {
      dist: {
        files: {
          'public/javascripts/app.js' : 
          [
            'assets/javascripts/components/**/*.js',
            'assets/javascripts/app.js'
          ]
        }
      }
    },
2

There are 2 best solutions below

0
On BEST ANSWER

The HelloWorld class is jsx so grunt-browserify needs to transform jsx to js using transform option.

browserify: {
  dist: {
    options: {
      transform: [ require('grunt-react').browserify ] // <-- this one
    },
    client: {
      src: [assets/javascripts/components/**/*.js, assets/javascripts/app.js], // sources files
      dest: 'public/javascripts/app.js' // output file
    }
  }
}

Here is a reference

Hope this helps.

1
On

I didn't go with Dhiraj's answer, but that led me to using reactify.

browserify: {
  options: {
    transform: ['reactify'],
    extensions: ['.jsx'],
    debug: true
  },
  dist: {
    files: {
      'public/javascripts/app.js' : 
      [
        'assets/javascripts/components/**/*.jsx',
        'assets/javascripts/app.jsx'
      ]
    }
  }
},