首页 > 解决方案 > 由于 webpack 版本错误,无法创建 React 项目

问题描述

当我创建 React 项目时,它有以下错误报告:

The react-scripts package provided by Create React App requires a dependency:

  "webpack": "4.44.2"

Don't try to install it manually: your package manager does it automatically.
However, a different version of webpack was detected higher up in the tree:

  /Users/lizhiyuan/node_modules/webpack (version: 4.46.0) 

Manually installing incompatible versions is known to cause hard-to-debug issues.

If you would prefer to ignore this check, add SKIP_PREFLIGHT_CHECK=true to an .env file in your project.
That will permanently disable this message but you might encounter other issues.

To fix the dependency tree, try following the steps below in the exact order:

  1. Delete package-lock.json (not package.json!) and/or yarn.lock in your project folder.
  2. Delete node_modules in your project folder.
  3. Remove "webpack" from dependencies and/or devDependencies in the package.json file in your project folder.
  4. Run npm install or yarn, depending on the package manager you use.

我去 package.json 文件,但是我没有在里面找到相关的代码。该文件的部分代码是:

"dependencies": {
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.1.2"
  },

此外,另一个提示是:

If nothing else helps, add SKIP_PREFLIGHT_CHECK=true to an .env file in your project.

但是,我在我的项目中找不到这样的“.env”文件。在我的 MacBook 上创建“.env”文件也很困难,因为系统阻止了这种行为。

有谁知道如何修理它?

标签: reactjswebpackversion

解决方案


是的,我听说 CRA 对 webpack 有问题。我建议您使用自定义 webpack 5 配置从头开始编写自己的项目。

.env但是,您可以通过在项目的根目录下创建一个名为的文件并在其中添加以下行来简单地解决此问题: SKIP_PREFLIGHT_CHECK=true. 重新启动你的应用程序,它会工作。MaxOs 不会妨碍您在 IDE 中创建 .env 文件(例如 vscode)。


推荐阅读