javascript - 模块解析失败:使用 webpack 5 时出现意外的令牌
问题描述
当我使用 webpack 5 编译我的 react 项目时,显示此错误:
[root@VM-0-16-centos cruise-web]# yarn build
yarn run v1.22.10
$ webpack --config config/dev.config.js
[webpack-cli] Compilation finished
assets by status 341 bytes [cached] 1 asset
./src/index.js 630 bytes [built] [code generated] [1 error]
ERROR in ./src/index.js 10:2
Module parse failed: Unexpected token (10:2)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|
| ReactDOM.render(
> <React.StrictMode>
| <Provider store={store}>
| {routes}
webpack 5.6.0 compiled with 1 error in 126 ms
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
这是我的index.js
:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import { Provider } from 'react-redux';
import reportWebVitals from './reportWebVitals';
import routes from './routes/routes';
import store from './store';
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
{routes}
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
reportWebVitals();
这是我的package.json
配置:
"scripts": {
"start": "react-scripts start",
"build": "webpack --config config/dev.config.js",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
这是dev.config.js
配置:
const path = require('path');
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
"style-loader",
"css-loader",
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [
[
"postcss-preset-env",
{
// Options
},
],
],
},
},
},
],
},
],
},
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'build'),
},
};
我应该怎么做才能解决这个问题?
解决方案
您需要为所有.js
文件定义一个规则并添加babel-loader
到其中:https ://github.com/babel/babel-loader
Webpack 的工作方式是你必须告诉它为每个特定的文件类型扩展名做什么(或者你定义你的规则)。Javascript,本质上是不理解的JSX
,您需要使用加载器,以便可以将其解析为常规且可用的 Javascript。Webpack 默认不理解 JSX。
推荐阅读
- wordpress - 标志显示两次
- python - 当我使用它时,pyinstaller 给了我一个错误
- sql - 如何更新oracle sql中的多行
- selenium - “无法调用“org.openqa.selenium.SearchContext.findElement..”,因为 SeleniumPage 对象模型中的“this.searchContext”为空
- azure-devops - 单击拉取请求中的完成按钮后,是否有办法在 Azure DevOps 中获取拉取请求 ID
- javascript - 如何根据 vuejs 中输入字段的错误验证禁用提交按钮?
- reactjs - 如何在 ReactJS 中对一次导入数据的列表进行分页
- tensorflow - 用于分割的官方标准化数据格式(张量流对象检测?)
- node.js - 由于模块 ibm-watson/auth 无法运行代码
- python - 如何在 Tortoise orm 中使用 CASE WHEN THEN ELSE