javascript - babel loader 无法识别 React 应用程序中的 ES6 代码

标签 javascript reactjs webpack babeljs babel-loader

我正在尝试使用 React 应用程序设置 webpack。就我而言,我没有使用 create-react-app,所以我尝试自己设置。我看到这个错误:

Not recognizing member declaration

还有这个:

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"
      }
    }

这是我的 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']
                    }
                }
            }
        ]

    }
}

这是我的组件使用的代码:

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

我对 webpack 和 loader 还很陌生,所以非常感谢您的帮助。

最佳答案

将代码更改为

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

}

关于javascript - babel loader 无法识别 React 应用程序中的 ES6 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55420511/

相关文章:

reactjs - React useEffect 有条件地运行

javascript - 表单提交时 &lt;iframe&gt; 背景发生变化

javascript - 从基于 JavaScript 的网页中提取表格

javascript - 如何在调整窗口大小时使表格响应?

ecmascript-6 - 仅转换 JSX

node.js - webpack 仅捆绑 firebase/database 而不是 firebase/auth

javascript - 当您有多个同名类时,使用 jQuery 选择特定类

javascript - 仅切换 Reactjs 中单击的菜单

javascript - Webpack 构建在 node_modules 上显示 TS 错误,而不是我的代码

angular - 随机重新加载 Angular 4(实时重新加载)