我第一次使用 react,如果我做的事情明显而且非常错误,请道歉。也就是说,我已经在这里和 github 上阅读了几个看起来相似的错误,但我找不到任何适合我的东西。这是完整的错误消息:
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。即使重命名,它也会被解析为 vanilla js 而不是 jsx,因为您的 webpack-config.js
,所以你应该做很多事情来修复它:
App.js
至App.jsx
, test: /\.js$/,
至test: /\.(js|jsx)$/,
在 webpack-config.js .babelrc
中也有错误。 : 你不想要 .js
那里,在"transform-class-properties"
之后. webpack-config.js
至webpack.config.js
这是一个显示此的教程:https://www.valentinog.com/blog/babel/ .此外,您可以使用 https://github.com/facebook/create-react-app这简化了所有这些并提供了一个很好的起始配置。
关于javascript - React - 模块解析失败 : Unexpected Token. 您可能需要适当的加载程序来处理此文件类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63769414/