Search code examples
gruntjsreactjsbrowserifygrunt-browserify

Parse error when running grunt-browserify on a React component


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'
          ]
        }
      }
    },

Solution

  • 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.