Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Learning ReactJS: Uncaught SyntaxError: Unexpected token import

I'm new to ReactJS. I'm trying out the code from egghead.io and I keep getting the following error:

Uncaught SyntaxError: Unexpected token import

I have loaded babel twice now and have followed along the lesson as described, but it just won't load into the html page. Here is the codes:

index.html

<!DOCTYPE html>
<html lang = "en">

   <head>
      <meta charset = "UTF-8">
      <title>Setup</title>
   </head>

   <body>
      <div id = "app"></div>
      <script src = "main.js"></script>
   </body>
</html>

main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App2';

ReactDOM.render(<App />, document.getElementById('app'))

app2.jsx

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

class App extends React.Component {
  render(){
    let txt = this.props.txt
    return <h1>{txt}</h1>
  }
}

App.propTypes = {
  txt: React.PropTypes.string,
  cat: React.PropTypes.number.isRequired
}

App.defaultProps = {
  txt: 'this is the default txt'
}

ReactDOM render(
  <App cat={5}/>,
  document.getElementById('app')
)

package.json

{
  "name": "es6-react-setup",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^0.14.3",
    "react-dom": "^0.14.3"
  },
  "devDependencies": {
    "babel-core": "^6.14.0",
    "babel-loader": "^6.2.5"
  }
}

Please help.

like image 924
muzzo Avatar asked Jun 06 '26 21:06

muzzo


1 Answers

After installing the Babel presets for ES6 and React you need to enable them either by creating a .babelrc file or by opting in in your package.json file.

(Confusing) docs here: http://babeljs.io/docs/usage/babelrc/

Example package.json entry enabling the presets:

"babel": {
    "presets": [
        [
          "env",
          {
            "modules": false
          }
        ],
        "react"
    ]
}
like image 108
Madbreaks Avatar answered Jun 09 '26 09:06

Madbreaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!