Ad

Syntax Error In ReactJS

- 1 answer

I'm starting to learn ReactJS and I'm following instructions in a book on getting started. My directory structure looks like this:

app/App.js
node_modules
index.html
package.json
webpack.config.js

I think that the culprit of the problem is this error message from CLI:

ERROR in ./app/App.js
Module build failed: SyntaxError: c:/code/pro-react/my-app/app/App.js: Unexpected token (6:6)
  4 |   render() {
  5 |     return (
> 6 |       <h1>Hello World</h1>
    |       ^
  7 |     );
  8 |   }
  9 | }

The contents of App.js are:

import React from 'react';

class Hello extends React.Component {
  render() {
    return (
      <h1>Hello World</h1>
    );
  }
}

React.render(<Hello />, document.getElementById('root'));

Here is the contents of package.json:

{
  "name": "my-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node_modules/.bin/webpack-dev-server --progress",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.4.5",
    "babel-loader": "^6.2.1",
    "webpack": "^1.12.11",
    "webpack-dev-server": "^1.14.1"
  },
  "dependencies": {
    "react": "^0.14.6"
  }
}

And the contents of webpack.config.js are:

module.exports = {
  entry: __dirname + "/app/App.js",
  output: {
    path: __dirname,
    filename: "bundle.js"
  },
  module: {
    loaders: [{
      test: /\.jsx?$/,
      loader: 'babel'
    }]
  }
};

I launch the application from CLI with the command:

npm start

And when I go to http://localhost:8080 in Dev Tools there is an error message:

GET http://localhost:8080/bundle.js 404 (Not Found)

But as I said, I think that the culprit is that it doesn't like the syntax so it doesn't make the bundle.js file. Please let me know what I'm doing wrong.

Ad

Answer

I think it happens because you are using babel-6 without babel presets, in this case you need babel-preset-es2015 and babel-preset-react.,

# For ES6/ES2015 support
npm install babel-preset-es2015 --save-dev

# Fot JSX support
npm install babel-preset-react --save-dev

then change webpack config

{
  test: /\.jsx?$/,
  loader: 'babel',
  query: {
    presets: ['es2015', 'react'],
  }
}

or instead of using query you can create .babelrc file with content

{
  "presets": ["es2015", "react"]
}

also you need install react-dom and use ReactDOM.render instaed or React.render

Ad
source: stackoverflow.com
Ad