Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 347
jmrosdev Avatar asked Jul 21 '26 02:07

jmrosdev


2 Answers

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"]
}
like image 134
dannyjolie Avatar answered Jul 23 '26 16:07

dannyjolie


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

 <script src="./index.js" type="text/babel"></script>
like image 24
Stepan Yakovenko Avatar answered Jul 23 '26 14:07

Stepan Yakovenko



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!