由于 webpack 版本错误,无法创建 React 项目

Posted

技术标签:

【中文标题】由于 webpack 版本错误,无法创建 React 项目【英文标题】:Fail to create React project due to wrong webpack version 【发布时间】:2021-09-25 04:46:43 【问题描述】:

当我创建 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"
  ,

另外,还有一个tips是:

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

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

有人知道怎么解决吗?

【问题讨论】:

【参考方案1】:

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

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

【讨论】:

以上是关于由于 webpack 版本错误,无法创建 React 项目的主要内容,如果未能解决你的问题,请参考以下文章

由于“Module not found: Error: Can't resolve”错误,Webpack 突然无法编译

无法在 create-react-app 中使用 css 模块

webpack版本问题

带有 Rails(webpacker)的 Vue 错误:“无法获取 /”

webpack TypeError:无法读取未定义的属性“已解决”

Webpack 2 - 无法在字符串上创建属性“映射”