首页 > 解决方案 > 找不到声明文件时如何使用模块

问题描述

我有一个使用 node.js 的打字稿项目。有一个模块我想使用 npm 包 country-code-lookup。

问题是它没有支持类型声明。但是,我仍然想使用它。

有没有可能我仍然可以在没有打字的情况下使用这个包。

import * as CountryCodeLookup from "country-code-lookup";

   const countryCodes = CountryCodeLookup.countries;
   console.log(countryCodes);

打字稿尝试编译时出现以下错误。

TS7016:找不到模块“国家代码查找”的声明文件。'/Users/kay/portal/node_modules/country-code-lookup/index.js' 隐含了一个 'any' 类型。尝试npm install @types/country-code-lookup它是否存在或添加一个新的声明 (.d.ts) 文件,其中包含declare module 'country-code-lookup';

标签: node.jsreactjstypescript

解决方案


如果您只需忽略此库的所有类型检查功能就没有问题,您有两种选择:

  1. 添加// @ts-ignore最重要的导入,如下所示:
// @ts-ignore
import * as CountryCodeLookup from "country-code-lookup";
  1. 创建一个带有any类型的声明文件,因此所有导入都被自动认为是any类型的。

为此,请创建一个文件src/types/country-code-lookup/index.d.ts 添加以下声明:

// country-code-lookup/index.d.ts
declare module 'country-code-lookup';

在此文件中,稍后您可以添加自己的类型定义。如果他们足够好,请推动他们做DefinitiveTyped,以便所有社区都可以使用和改进它!


推荐阅读