为什么 VS Code 从“hoist-non-react-statics/node_modules/@types/react”导入

IT技术 reactjs visual-studio-code node-modules intellisense
2021-05-19 20:22:00

我最近将我的 react 仓库移到了/client. 我在安装时使用 yarn install 安装了 node_modules/client

VS 代码智能感知建议我在导入像这样的react-hooks时导入 fromhoist-non-react-statics/node_modules/@types/react而不是 from 当我使用编译时,这会导致以下错误reactuseEffectuseRefyarn start

未找到module:无法解析 'hoist-non-react-statics/node_modules/@types/react'

我的 package.json 中没有“hoist-non-react-statics”作为依赖项。我的 package.json 依赖项如下:

"dependencies": {
    "@auth0/auth0-react": "^1.6.0",
    "@hookform/resolvers": "^2.7.1",
    "@reduxjs/toolkit": "^1.6.1",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "@types/jest": "^24.0.0",
    "@types/node": "^12.0.0",
    "@types/qs": "^6.9.7",
    "@types/react": "^16.9.0",
    "@types/react-dom": "^16.9.0",
    "@types/react-redux": "^7.1.7",
    "@types/react-slider": "^1.3.1",
    "@types/react-table": "^7.7.2",
    "clsx": "^1.1.1",
    "final-form": "^4.20.2",
    "final-form-calculate": "^1.3.2",
    "lodash": "^4.17.21",
    "qs": "^6.10.1",
    "rc-checkbox": "^2.3.2",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-final-form": "^6.5.3",
    "react-hook-form": "^7.12.2",
    "react-redux": "^7.2.4",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.3",
    "react-slider": "^1.3.1",
    "react-table": "^7.7.0",
    "react-truncate": "^2.4.0",
    "typescript": "~4.1.5",
    "yup": "^0.32.9"
  },

与react相关的@types 似乎是一个问题。我在react-reduxgithub repo上提交了一个问题

yarn upgrade @types/react修复它。为了更好的衡量,所有的包都应该升级yarn upgrade --latest或只升级所有类型yarn upgrade --latest --pattern "@types"

https://github.com/reduxjs/react-redux/issues/1806

4个回答

在降级/升级 VSCode 和 TypeScript 版本后,我发现这个问题发生在最新的 TypeScript 版本(用 4.4.2 测试,但可能存在于整个 4.4.x 分支中)。这个问题在 4.3.5 中似乎不存在。您可以执行以下操作:

  • 将 VSCode 更新到最新版本
  • 确保您安装了 TS 4.3.5 或更早版本(全局或在工作区项目中)
  • 打开任何带有.ts扩展名的文件
  • 使用状态栏中的下拉菜单选择 TypeScript 版本。您要么选择 Workspace 版本,要么选择全局版本,而不是 VSCode 的预装版本。

有关最后一步的说明,请参见下图: 在此处输入图片说明

我的typescript项目也有同样的问题。使用 npm:

npm i @types/react@latest

然后重启vscode

我有同样的问题。升级 @types/react 没有帮助。我不得不将其删除以解决问题。一些我仍然从某个地方获得类型定义的方式。这才刚刚开始发生在我已经工作了一年的项目上。不确定它是否来自 VsCode 更新或升级在几周前有react。

该错误发生在 VsCode windows 和 mac 上。

这将在 TypeScript 的新版本 (4.5) 中修复。请参阅:https : //github.com/microsoft/TypeScript/issues/45784 https://github.com/microsoft/TypeScript/pull/45792

在此next版本发布之前,您可以使用该版本。

npm i typescript@next

不要忘记重新生成锁定文件以确保安装了正确的版本。