问题描述
我第一次使用react,所以如果我做的很明显并且做错了事,那么我深表歉意。就是说,我已经在这里和github上阅读了一些类似的bug,但找不到适合我的东西。这是完整的错误消息:
ERROR in ./src/frontend/src/components/App.js 6:15
Module parse Failed: Unexpected token (6:15)
You may need an appropriate loader to handle this file type.
| class App extends Component{
| render() {
> return <h1>React App</h1>
| }
| }
@ ./src/frontend/src/index.js 1:0-35
import React,{ Component } from 'react';
import ReactDOM from 'react-dom';
class App extends Component{
render() {
return <h1>React App</h1>
}
}
ReactDOM.render(<App />,document.getElementById('app'));
我感觉我的webpack-config.js出了点问题,但是我直接从我正在使用的教程中复制了它,所以我不确定为什么会出错。这里是供参考:
module.exports = {
module: {
rules: [
{
test: /\.js$/,exclude: /node_modules/,use: {
loader: "babel-loader"
}
}
]
}
}
这是我来自package.json的软件包依赖项:
"dependencies": {
"prop-types": "^15.7.2","react": "^16.13.1","react-dom": "^16.13.1"
},
最后是我的.babelrc
{
"presets": ["@babel/preset-env","@babel/preset-react"],"plugins": ["transform-class-properties".js]
}
我真的不知道发生了什么事,因此非常感谢您的帮助。如果我遗漏了任何有用的相关信息,请告诉我。谢谢。
解决方法
错误来自以下行:return <h1>React App</h1>
,因为<h1>...</h1>
是无效的javascript。由于您的webpack-config.js
,即使重命名也将被解析为普通js而不是jsx,所以您应该做很多事情来解决它:
- 将
App.js
重命名为App.jsx
, - 将webpack-config.js中的
test: /\.js$/,
更新为test: /\.(js|jsx)$/,
- 我认为您的
.babelrc
中也存在错误:您不希望.js
之后出现"transform-class-properties"
。 - 将
webpack-config.js
重命名为webpack.config.js
以下是显示此内容的教程:https://www.valentinog.com/blog/babel/。另外,您可以使用https://github.com/facebook/create-react-app简化所有步骤并提供出色的启动配置。