无法导入外部NPM包以创建angular库

stszievb  于 2023-05-18  发布在  Angular
关注(0)|答案(2)|浏览(209)
  • package.json首先我这样做了,
{
  "name": "crypto-local-storage",
  "version": "0.0.1",
  "peerDependencies": {
    "@angular/common": "^12.2.0",
    "@angular/core": "^12.2.0",
    "crypto-js": "^3.1.8",
    "secure-web-storage": "^1.0.2"
  },
  "dependencies": {
    "tslib": "^2.3.0"
  },
  "devDependencies": {
    "@types/crypto-js": "^4.0.2"
  }
}

其次,我做了这个

{
  "name": "crypto-local-storage",
  "version": "0.0.1",
  "peerDependencies": {
    "@angular/common": "^12.2.0",
    "@angular/core": "^12.2.0"
    
  },
  "dependencies": {
    "tslib": "^2.3.0",
    "crypto-js": "^3.1.8",
    "secure-web-storage": "^1.0.2"
  },
  "devDependencies": {
    "@types/crypto-js": "^4.0.2"
  }
}

但是在我的服务文件中,当我导入secure-web-storage时,就像这样
import * as SecureStorage from 'secure-web-storage';我收到了这样的信息

TS7016: Could not find a declaration file for module 'secure-web-storage'.
 'D:/AMS/crypto-local-storage/projects/crypto-local-storage/node_modules/secure-web-storage/secure-storage.js' 
implicitly has an 'any' type.  
Try `npm i --save-dev @types/secure-web-storage` if it exists or add a new declaration (.d.ts) file containing 
`declare module 'secure-web-storage';`

secure-web-storage不包含任何@types/secure-web-storage文件。那么,如何才能避免这个错误呢?我没有得到任何明确的答案后,谷歌这么多。
我的文件夹结构可能对你有帮助,
My Folder Structure Image

kr98yfug

kr98yfug1#

如果运行npm install -D @types/secure-web-storage不能解决问题,请使用require代替import

const secureWebStorage= require('secure-web-storage');
vsdwdz23

vsdwdz232#

您也可以尝试在src文件夹中创建一个typings.d.ts文件,并手动为其添加类型。

declare module 'secure-web-storage' {
    export function someFunction(): void;
}

然后在你的ts文件里,你可以用类似-

import { someFunction } from 'secure-web-storage';

通过使用这种方法,您可以保存大量的捆绑大小,而不是使用-

const secureWebStorage= require('secure-web-storage');

这占用了大量的束大小并使应用程序变慢。你可以在这里阅读更多关于这个-https://web.dev/commonjs-larger-bundles/

相关问题