TypeScript 引入 第三方包找不到无法找到模块

12,644 阅读1分钟
解决办法:

以 react-router-dom 模块为例

image.png

解决办法有两种

方法一

根据报错提示尝试安装该库的TypeScript版本 (该库的 ts 声明文件),也就是在该库的名称前加上 @types/
本例子为 npm install @types/react-router-dom
其它库如下:

npm install @types/XXX
or
yarn add @types/XXX

但是,不是所有的第三方库都有 TypeScript 的版本,所以方法一不能保证百分百有效,如果方法一不奏效,那么我们来看一下方法二。

方法二

(在方法一可行的情况下,推荐使用方法一)

1、在项目根目录新建 typings 文件夹。

2、在 tsconfig.json 里的 include 添加上 typings

image.png

3、在 typings 文件夹里新建类型声明文件,格式为 XXX.d.ts 本例子为 react-router-dom.d.ts

image.png

4、声明模块类型

declare module 'XXX' {
  const content: any
  export = content
}

本例子为:

declare module 'react-router-dom' {
  const content: any
  export = content
}

效果如下

image.png