jmrosdev
jmrosdev

Reputation: 123

Unexpected token - React babel

I am new to the world react and I have a bug that will not let me progress. This is my webpack

module.exports = {
entry: [
'./src/index.js'
],
output: {
path: __dirname,
publicPath: '/',
filename: 'bundle.js'
},
module: {
 loaders: [{
  exclude: /node_modules/,
  loader: 'babel'
 }]
}
resolve: {
 extensions: ['', '.js', '.jsx']
},
devServer: {
 historyApiFallback: true,
 contentBase: './'
}
};

This is my code js

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

import SearchBar from './components/search_bar';

const API = '';

const App = () => {
 return (
     <div>
         <SearchBar />
     </div>
 );
}

ReactDOM.render(<App />, document.querySelector('.container'));

This is error https://gyazo.com/be83135be6f0e7b8ca0c2852536c792f

I tried this solution but it does not work babel-loader jsx SyntaxError: Unexpected token

This is a project https://github.com/jmrosdev/Practicas/tree/master/React/youtube-search

Bye and thanks!

Upvotes: 3

Views: 8727

Answers (3)

Stepan Yakovenko
Stepan Yakovenko

Reputation: 9206

I had the same error and the reason was that type="text/babel" was missing:

 <script src="./index.js" type="text/babel"></script>

Upvotes: 1

Dimitris Karagiannis
Dimitris Karagiannis

Reputation: 9358

You are most likely not using the babel-react preset.

Make sure you have it in your dependencies, in your package.json file (if you don't have it do npm install babel-core babel-preset-es2015 babel-preset-react -D ) and in the loaders section of your webpack.config.js make this line

    module: {
     loaders: [{
      exclude: /node_modules/,
      loader: 'babel'
     }]
    }

into this

module: {
 loaders: [{
  exclude: /node_modules/,
  loader: 'babel'
 },
{
        test: /\.js$/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015', 'react']
        }

}]

Upvotes: 0

dannyjolie
dannyjolie

Reputation: 11339

It fails because Babel doesn't recognize the JSX syntax. So you need to install a babel preset or two:

npm install --save-dev babel-preset-react babel-preset-es2015

Create the .babelrc file at the root of your project if you don't already have one. It should have this content

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

Upvotes: 11

Related Questions