我第一次使用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。即使重命名这个is也会被解析为vanilla-js而不是jsx,因为你的webpack-config.js
,所以你应该做很多事情来修复它:
- 将CCD_ 4重命名为CCD_
- 在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这简化了所有这些,并提供了一个很好的启动配置。
在webpack.config.js中添加了这段代码,将jsx解析为js。访问Can';t在React.js 中解析模块(未找到(
module.exports = {
//...
resolve: {
extensions: ['.js', '.jsx']
}
};