[英]TypeScript error: Cannot find module 'React'
I've been trying to compile my project for several hours, I searched all over the internet, but I still don't understand why it doesn't work.我一直在尝试编译我的项目几个小时,我在整个互联网上进行了搜索,但我仍然不明白为什么它不起作用。
I just run npx tsc
but I get this error:我只是运行
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: 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: src/index.ts:
import lodash from 'lodash';
import * as React from 'React';
packages.json:包。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"
}
}
What gives?是什么赋予了?
You should probably install react
as a dependency and not a devDependency
.您可能应该将
react
作为依赖项而不是devDependency
。 Also, make the react import the first line in the file.此外,使反应导入文件中的第一行。
Apart from installing react as a dependency by running,除了通过运行将 react 安装为依赖项之外,
npm i react
you might want to import the default exported module instead.您可能想要导入默认导出的模块。
import React from 'react';
And on your tsconfig.json
, you can set allowSyntheticDefaultImports
as true
.在您的
tsconfig.json
上,您可以将allowSyntheticDefaultImports
设置为true
。
"allowSyntheticDefaultImports": true
In addition, you may read more about integrating TypeScript with React .此外,您可以阅读更多关于将TypeScript 与 React集成的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.