React,Typescript-找不到模块...或其对应的类型声明 [英] React, Typescript - Cannot find module ... or its corresponding type declarations

查看:4878
本文介绍了React,Typescript-找不到模块...或其对应的类型声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用vs代码中的create-react-app和yarn 2创建了一个新项目.像这样导入每个已安装的库时,编辑器会引发错误:

I created a new project using create-react-app and yarn 2 in vs code. The editor throws errors while importing every installed library like this:

找不到模块反应"或其相应的类型声明.

Cannot find module 'react' or its corresponding type declarations.

项目编译并成功运行,但错误仍然存​​在.当我将文件扩展名更改为 .js .jsx 形式. ts .tsx 时,错误消失了.我该如何解决打字稿文件的问题?

The project compiles and runs successfully but the errors are still there. When I change the file's extension to .js and .jsx form .ts and .tsx, the errors disappear. How should I solve this problem for typescript files?

推荐答案

您需要为所安装的库安装类型.通常,您应该这样做:

You need to install types for libraries you install. generally you should do:

npm install @types/libName // e.g. npm install @types/react-leaflet

有时 DefinitelyTyped 回购中没有可用的类型,您会遇到 npm ERR!找不到404:@ types/my-untyped-module @ latest .在这种情况下,您可以做几件事:

Some times there's no types available in DefinitelyTyped repo and you encounter npm ERR! 404 Not Found: @types/my-untyped-module@latest. You can do several things in this occasion:

1-在您的项目根目录中创建一个 decs.d.ts 文件并写入:

1- Create a decs.d.ts file in root of your project and write in it:

    declare module "libName" // e.g declare module 'react-leaflet'

2-或仅使用 @ ts-ignore 来抑制该错误:

2- Or simply suppress the error using @ts-ignore:

// @ts-ignore  
import Map from 'react-leaflet'

3-或者您也可以帮自己一个忙,并在绝对输入回购.

3- Or you can do yourself and others a favor and add the library types in DefinitelyTyped repo.

如果仍然无法使用,我首先建议您使用最新版本的Typescript.如果这样做,请关闭编辑器,删除 node_modules 文件夹,然后再次安装依赖项( npm install yarn install ),然后再次检查.

If it still doesn't work, I firstly recommend that you use a recent version of Typescript. if you do, then close your editor, delete node_modules folder and install the dependencies again (npm install or yarn install) and check it again.

这篇关于React,Typescript-找不到模块...或其对应的类型声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆