Angular库导入外部NPM包secure-web-storage时遭遇TS7016声明文件缺失错误的解决方案咨询
解决Angular库中导入
secure-web-storage的TS7016类型错误 我刚好遇到过类似的问题——当使用没有官方TypeScript类型声明的npm包时,TypeScript总会抛出这类“找不到声明文件”的错误。针对你的情况,我们可以通过自定义类型声明文件来彻底解决这个问题,具体步骤如下:
1. 创建自定义类型声明文件
因为secure-web-storage既没有自带类型声明,也没有社区维护的@types/secure-web-storage包,我们需要手动为它写一个基础的类型定义:
- 进入你的Angular库项目目录
projects/crypto-local-storage/src,新建一个types文件夹(如果不存在的话); - 在
types文件夹中创建secure-web-storage.d.ts文件,写入以下内容:
这个定义覆盖了declare module 'secure-web-storage' { class SecureWebStorage { constructor(storage: Storage, options?: { hash?: string; encryption?: boolean; secret: string; }); getItem(key: string): any; setItem(key: string, value: any): void; removeItem(key: string): void; clear(): void; key(index: number): string | null; length: number; } export = SecureWebStorage; }secure-web-storage的核心API,你可以根据自己实际用到的方法补充或调整字段。
2. 让TypeScript识别自定义类型
打开库项目下的tsconfig.lib.json文件(路径是projects/crypto-local-storage/tsconfig.lib.json),修改compilerOptions配置:
- 如果存在
typeRoots字段,添加自定义类型文件夹的路径:"typeRoots": [ "../../node_modules/@types", "./src/types" ] - 如果没有
typeRoots,就在include字段中加入类型文件的路径:
这样TypeScript编译时就能找到我们自定义的类型声明了。"include": [ "src/**/*.ts", "src/types/**/*.d.ts" ]
3. 验证配置并使用
回到你的service文件,保持原导入语句:
import * as SecureStorage from 'secure-web-storage';
现在你可以正常实例化并使用这个库了,比如:
const secureStorage = new SecureStorage(localStorage, { secret: 'your-encryption-secret', encryption: true });
此时TS7016的错误应该已经消失。
补充:关于package.json的配置建议
你调整后的第二种配置更合理——把secure-web-storage放在dependencies中,因为你的库直接依赖这个包运行,不需要让使用者额外安装(如果放在peerDependencies,则要求使用者自行安装,适合Angular核心库这类需要版本对齐的依赖)。
内容的提问来源于stack exchange,提问作者Sefat Anam
相关产品推荐
相关产品推荐

