Search code examples
javascriptreactjswebpackbabeljsbabel-loader

babel loader not recognizing ES6 code in React app


I am trying to setup webpack with a react application. In my case, I am not using create-react-app, so I am trying to setup things myself. I am seeing this error:

Not recognizing member declaration

and this:

Not recognizing ()=> syntax

This is what I have in package.json: 

  {
      "name": "testapp",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "webpack": "webpack"
      },
      "author": "",
      "license": "ISC",
      "dependencies": {
        "babel-core": "^6.26.3",
        "babel-loader": "^7.1.5",
        "babel-preset-env": "^1.7.0",
        "babel-preset-react": "^6.24.1",
        "react": "^16.8.6",
        "react-dom": "^16.8.6",
        "webpack": "^4.29.6",
        "webpack-cli": "^3.3.0"
      }
    }

This is my webpack.config.js:

module.exports = {
    mode: 'development',
    context: __dirname,
    entry: './index.js',
    output: {
        path: __dirname + '/dist',
        filename: 'bundle.js'
    }, 
    watch: true,
    module: {
        rules: [
            {
                test: /\.js$/, 
                exclude: /(node_modules)/, 
                use: {
                    loader: 'babel-loader', 
                    options: {
                        presets: ['babel-preset-env', 'babel-preset-react']
                    }
                }
            }
        ]

    }
}

And this is the code am using for my component:

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

class App extends React.Component {

    state = {
        posts: []
    }


    componentDidMount = () => {
        const posts = fetch('https://jsonplaceholder.typicode.com/posts')
            .then(response => response.json())
            .then(data => alert(data))

    }

    render() {
        return (
            <div>this is home</div>    
        )
    }
}

export default App

I am still new to webpack and loaders, so any help is appreciated.


Solution

  • Try using babel class properties plugin.