httpNick
httpNick

Reputation: 2624

ES6 with React and Browserify

So I am trying to use ES6's import statement with React and browserify to create a web app. I am having some hurdles and here is the first one.

Here is my index.js:

import React from 'react';
import ReactDOM from 'react-dom';

var Start = React.createClass({
  getText: function() {
    return 'hi'
  },

  render: function() {
    return (
      <h1 className="jumbotron">{this.getText()}</h1>
    );
  }
});

ReactDOM.render(
  <Start />,
  document.getElementById('example')
)

Here is my index.html:

<html>
  <head>
    <link rel="stylesheet" href="../../bower_components/bootstrap/dist/css/bootstrap.min.css">
  </head>
  <body>
    <div id="example"></div>
    <script src="../build/bundle.js"></script>
  </body>
</html>

Here are my node dependencies:

  "dependencies": {
    "babel-preset-es2015": "^6.1.18",
    "babel-preset-react": "^6.1.18",
    "babelify": "^7.2.0",
    "react": "^0.14.3",
    "react-dom": "^0.14.3"
  }

Here is the command I use to try to transpile my code with watchify:

watchify -t [ babelify --presets [ react ] ] index.js -o ../build/bundle.js

Here is the error I get:

/Users/httpnick/react/csgo-cache/public/js/index.js:1
import React from 'react';
^
ParseError: 'import' and 'export' may appear only with 'sourceType: module'

I was fighting this all weekend and not sure what to do. If I remove the imports and just use require()s it works, but import just does not like to work for me. Any help fixing this issue or things I could check would be greatly appreciated.. I really want to get into ES6 with React.

Upvotes: 0

Views: 1615

Answers (1)

Tahir Ahmed
Tahir Ahmed

Reputation: 5737

I think you are missing a .babelrc file in your project structure which could contain:

{
  "presets": ["es2015"],
  "plugins": ["transform-react-jsx"]
}

Hope this helps.

EDIT:

As you are using CLI, you could pass in the missing es2015 like so:

watchify -t [ babelify --presets [ es2015 react ] ] index.js -o ../build/bundle.js

(notice the additional es2015 in the line above, that is the only difference from your code).

Upvotes: 1

Related Questions