TypeScript错误:找不到模块“ React”

时间:2019-10-28 13:17:23

标签: typescript tsc

我一直在尝试编译我的项目几个小时,我在Internet上进行了搜索,但是我仍然不明白为什么它不起作用。

我刚运行npx tsc,但出现此错误:

$ npx tsc
src/index.ts:2:24 - error TS2307: Cannot find module 'React'.

2 import * as React from 'React';
                         ~~~~~~~


Found 1 error.

tsconfig.json:

{
  "compilerOptions": {
    "moduleResolution": "node",
    "target": "es6",
    "module": "commonjs",
    "esModuleInterop": true,
    "lib": [
      "es2015",
      "es2016",
      "es2017",
      "dom"
    ],
    "strict": true,
    "sourceMap": true,
    "declaration": true,
    "declarationDir": "dist/types",
    "outDir": "dist/lib",
    "typeRoots": [
      "node_modules/@types"
    ],
    "jsx": "react",
    "noResolve": false,
    "allowJs": false,
    "forceConsistentCasingInFileNames": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": true,
    "strictNullChecks": true
  },
  "include": [
    "src"
  ],
  "exclude": [
    "node_modules",
    "dist",
    "playground"
  ]
}

src / index.ts:

import lodash from 'lodash';
import * as React from 'React';

packages.json:

{
  "files": [
    "dist"
  ],
  "devDependencies": {
    "@types/lodash": "^4.14.144",
    "@types/node": "^12.11.7",
    "@types/react": "^16.9.11",
    "lodash": "^4.17.15",
    "react": "^16.11.0",
    "ts-node": "^8.4.1",
    "typescript": "^3.6.4"
  }
}

有什么作用?

2 个答案:

答案 0 :(得分:0)

您可能应该将react作为依赖而不是devDependency安装。 另外,使react导入文件的第一行。

答案 1 :(得分:0)

除了安装之外,通过运行

作为依赖项
npm i react

您可能想导入默认的导出模块。

import React from 'react';

tsconfig.json上,您可以将allowSyntheticDefaultImports设置为true

"allowSyntheticDefaultImports": true

此外,您可能会了解有关集成TypeScript with React的更多信息。