【问题标题】:Importing Javascript library (jsencrypt) into Angular 2 app将 Javascript 库 (jsencrypt) 导入 Angular 2 应用程序
【发布时间】:2023-03-16 12:58:01
【问题描述】:

我浏览了所有围绕此问题的教程,但无法找到解决方案。先来点背景。我有一个 Angular 2 应用程序,我需要使用这个 JS 库进行加密:https://github.com/travist/jsencrypt

首先,我使用以下行安装了 jsencrypt 节点模块:npm install --save jsencrypt。这行得通,并且可以在我的 node_modules 文件夹中找到 jsencrypt 模块。

一些教程告诉我创建一个 src/typings.d.ts 文件,然后添加以下行:declare module 'jsencrypt';

然后,在我的 comonents.ts 文件中,我使用以下行导入它: 导入 * as JSEncrypt from 'jsencrypt';

我也尝试添加

进入我的 .html 文件。

在我的 .component 文件的初始化中,我尝试声明一个简单的 JSEncrypt 对象: var decrypt = new JSEncrypt();

控制台显示此错误: TypeError: Object is not a constructor (evalating 'new WEBPACK_IMPORTED_MODULE_4_jsencrypt()')

所以我假设它无法识别 jsencrypt 模块。

我只使用 Angular 几天,所以我对 Angular 应用程序的结构组件的所有术语和基本理解非常陌生。任何帮助是极大的赞赏。

以本教程为起点: https://hackernoon.com/how-to-use-javascript-libraries-in-angular-2-apps-ff274ba601af

【问题讨论】:

    标签: javascript angular typescript import jsencrypt


    【解决方案1】:

    我对之前需要使用的任何其他 Javascript 模块都使用了相同的步骤,并且一切正常。

    1. ng 新项目名称
    2. cd 项目名称
    3. npm install --save jsencrypt

    正如您所提到的,此时您已经拥有了一个完整的 Angular 应用程序,至少在 node_modules 中安装了包 jsencrypt。接下来的步骤是摆脱 Typescript 编译消息,尽管您可以跳过它们,但它仍然可以工作:

    src 文件夹中,创建一个名为 @types 的文件夹,并在其中创建另一个包名为 jsencrypt 的文件夹,最后,创建一个 index.d.ts 里面。这样:

    • application_root_folder/src/@types/jsencrypt/index.d.ts

    文件的内容应该只是模块的声明:

    declare module 'jsencrypt';
    

    最后,为了使用包,在任何 .ts 文件中,例如在我的例子中的 app.component.ts 文件中,您可以导入模块并使用它:

    import { Component } from '@angular/core';
    import * as JsEncryptModule from 'jsencrypt';
    
    @Component({
        selector: 'app-root',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.css']
    })
    export class AppComponent {
        title = 'app';
    
        constructor() {
            var encrypt = new JsEncryptModule.JSEncrypt();
            console.log(encrypt);
        }
    }
    

    你可以检查你的浏览器控制台,你有一个包含模块/包提供的所有属性和方法的对象:

    我不会详细介绍包使用本身的细节,因为我不知道,我认为这不是问题的重点。希望对你有帮助!

    【讨论】:

      【解决方案2】:

      在反应中(创建反应应用程序)用 .d.ts 打开这个文件

      并添加这一行declare module 'jsencrypt'; .

      【讨论】:

        【解决方案3】:
        import { JSEncrypt } from 'jsencrypt';
        

        试试这个。它只导入 JSEncrypt 类。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-09-25
          • 2016-11-04
          • 2016-11-03
          • 1970-01-01
          • 1970-01-01
          • 2017-12-28
          • 2018-02-22
          • 2017-06-21
          相关资源
          最近更新 更多