Reputation: 121
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.
Upvotes: 3
Views: 17542
Reputation: 19539
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"
]
}
Upvotes: 3
Reputation: 3056
import
is the ES6 syntax. You need to npm install babel-preset-es2015 babel-preset-react --save-dev
to tell babel compile your ES6
and React
code.
you can load 2 packages in your webpack.config.js
file :
module.exports = {
entry: './main.js',
output: {
path: './',
filename: 'index.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
I hope it will help you.
Upvotes: 0