我正在创建一个 Angular 8 库,它将利用 insane.js npm 包。因为 insane 是 JavaScript,所以我需要对其进行修改,以便我的 typescript 服务能够识别 insane 函数。我使用 dts-gen 创建一个 insane.d.ts 文件,因为没有 @types/insane 包。但是,除非将 insane.d.ts 文件放在/node_modules/insane/文件夹中,否则我无法在服务中使用导入。也就是说,我不知道如何将此文件放入我的代码中并识别这个疯狂的函数。每次我将文件移出该目录时,我都会在导入行中收到一条错误消息:
Could not find a declaration file for module 'insane'. 'c:/TFS/repo/amrock-simple-mde/projects/simple-mde/node_modules/insane/insane.js' implicitly has an 'any' type.
我提供了 stackblitz 链接 here帮助描述我正在经历的事情。我希望它有帮助。查看共享文件夹下的 SanitizerService 以了解我想要做什么。我正在尝试做一些事情,以达到以下效果:
import { Injectable } from '@angular/core';
import * as insane from 'insane'; // line where error is
@Injectable({
providedIn: 'root'
})
export class SanitizerService {
constructor() { }
sanitize(content: string): string {
return insane(content, {
allowedAttributes: {
a: ['name', 'target']
}
});
}
}
我希望导入能够识别 insane.d.ts,但事实并非如此。谁能帮我弄清楚我错过了什么?
最佳答案
您需要使用 declare module
statement为此:
declare module 'insane' {
// ...
}
基本上将整个 .d.ts
文件包装在 declare module
block 中,并删除所有现有的 declare
关键字,因为这些关键字在内部无效一个声明模块
block 。
其次,确保 TypeScript 包含 .d.ts
文件。通常,最简单的方法是在 tsconfig.json
的 include
选项中指定它。
关于javascript - 如何在 Angular 库的 node_modules 文件夹之外使用 *.d.ts?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57911437/