打字稿:找不到模块'反应'

AJc*_*dez 13 typescript reactjs

我不明白为什么它找不到它.

$ cat tsconfig.json

{
  "compilerOptions": {
    "sourceMap": true,
    "target": "es6",
    "jsx": "react",
    "types": [
      "lodash",
      "react",
      "react-dom"
    ]
  }
}

$ tree node_modules/@types

node_modules/@types/
??? lodash
?   ??? README.md
?   ??? index.d.ts
?   ??? package.json
?   ??? types-metadata.json
??? react
?   ??? README.md
?   ??? index.d.ts
?   ??? package.json
?   ??? types-metadata.json
??? react-dom
    ??? README.md
    ??? index.d.ts
    ??? package.json
    ??? server.d.ts
    ??? types-metadata.json
Run Code Online (Sandbox Code Playgroud)

导入组件文件.

// src/components/component.tsx

import * as React from "react";
Run Code Online (Sandbox Code Playgroud)

是什么赋予了?

Iho*_*lyk 13

我遇到过同样的问题.你只需要安装@types:

npm i -D @types/react
Run Code Online (Sandbox Code Playgroud)

  • 其中,绝对n00bs(me)与`npm install --save-dev @ types/react`相同.从[文档](https://docs.npmjs.com/cli/install):"*-D, - save-dev:Package将出现在你的devDependencies.*" (6认同)

rks*_*tar 10

如果你没有使用typescript 2.1,你应该升级到它.看起来你正在使用@types的2.x版本.

这是tsconfig.json我正在使用的工作文件:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "noResolve": false,
    "noImplicitAny": false,
    "removeComments": true,
    "sourceMap": true,
    "allowJs": true,
    "jsx": "react"
  },
  "exclude": [
    "./node_modules/**/*"
  ]
}
Run Code Online (Sandbox Code Playgroud)

自从我解决了你遇到的同样问题以来已经过了几天,但我认为这里的关键是"moduleResolution": "node""allowJs": true.


小智 7

在版本 2.4.* 上,此错误的负责配置条目(在大多数情况下)是:

"compilerOptions": {
          ...
          "moduleResolution": "node" <---------- this entry
          ...
}
Run Code Online (Sandbox Code Playgroud)

我希望它可以帮助某人!

  • 那有什么办法解决呢? (6认同)

小智 5

为了解决来自 eslint 规则的打字稿“找不到模块‘反应’ ”,

您需要安装@types/react

$ npm i -D @types/react

或者

$ yarn add -D @types/react

并在您的.eslintrc 文件中添加扩展数组 react 插件:

...
extends: [
        'plugin:react/recommended',
        ...  
],
Run Code Online (Sandbox Code Playgroud)

希望大家都能看得更清楚:D