typescript报错:Could not find a declaration file for module xxx

栏目: NodeJs 发布时间:2023-02-24

在 typescript 项目中我们经常遇到这样的报错:Could not find a declaration file for module xxx。

遇到这样的报错要怎么处理呢?

先来看一个报错示例,以 nprogress 为例:

ERROR in src/router/index.ts:2:23

TS7016: Could not find a declaration file for module 'nprogress'. '/Users/teng/code/node_modules/nprogress/nprogress.js' implicitly has an 'any' type.
  Try `npm i --save-dev @types/nprogress` if it exists or add a new declaration (.d.ts) file containing `declare module 'nprogress';`
    1 | import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
  > 2 | import NProgress from 'nprogress';
      |                       ^^^^^^^^^^^
    3 | import i18n from '@/lang';
    4 |
    5 | const routes: Array<RouteRecordRaw> = [];

请仔细看上述报错信息,说的很清楚,缺少声明文件。

解决方案

上述报错信息已经给出了解决方案:

npm i --save-dev @types/nprogress

我们到 node_modules 目录下看一下安装好的 @types/nprogress 目录,在该目录下找到 index.d.ts 文件,内容如下:

// Type definitions for NProgress 0.2
// Project: https://github.com/rstacruz/nprogress
// Definitions by: Judah Gabriel Himango <https://github.com/JudahGabriel>, Ovyerus <https://github.com/Ovyerus>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1

declare namespace nProgress {
  interface NProgressOptions {
      minimum: number;
      template: string;
      easing: string;
      speed: number;
      trickle: boolean;
      trickleSpeed: number;
      showSpinner: boolean;
      parent: string;
      positionUsing: string;
      barSelector: string;
      spinnerSelector: string;
  }

  interface NProgress {
      version: string;
      settings: NProgressOptions;
      status: number | null;

      configure(options: Partial<NProgressOptions>): NProgress;
      set(number: number): NProgress;
      isStarted(): boolean;
      start(): NProgress;
      done(force?: boolean): NProgress;
      inc(amount?: number): NProgress;
      trickle(): NProgress;

      /* Internal */

      render(fromStart?: boolean): HTMLDivElement;
      remove(): void;
      isRendered(): boolean;
      getPositioningCSS(): 'translate3d' | 'translate' | 'margin';
  }
}

declare const nProgress: nProgress.NProgress;
export = nProgress;

以上就是 typescript报错:Could not find a declaration file for module xxx 的解决方法,祝你好运!

本文地址:https://www.tides.cn/p_node-could-not-find-a-declaration-file-for-module-nprogress

标签: typescript