加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何在Angular 2中导入非核心npm模块,例如(使用加密库)?

发布时间:2020-12-17 07:24:28 所属栏目:安全 来源:网络整理
导读:在我的Angular 2应用程序(SystemJS模块管理器,作为脚本语言的Typescript)中,我需要导入一个npm模块来处理加密(Crypto-JS; Forge-JS或任何其他服务目的) 在CryptoJS的情况下,通过npm install *安装后我尝试添加: script src="node_modules/crypto-js/crypto-
在我的Angular 2应用程序(SystemJS模块管理器,作为脚本语言的Typescript)中,我需要导入一个npm模块来处理加密(Crypto-JS; Forge-JS或任何其他服务目的)

在CryptoJS的情况下,通过npm install *安装后我尝试添加:

<script src="node_modules/crypto-js/crypto-js.js"></script>

in index:html.

在我的服务(app / services / my-service.service.ts)我通过它导入它

import {CryptoJS} from 'node_modules/crypto-js/crypto-js.js' // or /aes.js --> same issue

但是,导入无法正常工作

console.log(CryptoJS);

打印未定义.

我还尝试添加模块路径

System.config({
     // ...
     map: {
        CryptoJS
    }
}

并在我的服务中导入它

import {CryptoJS} from 'cryptoJs';

虽然我不确定我应该在SystemJS配置中实际放入什么,但我尝试过的解决方案都没有.

编辑我也试过……

// import ... as to overcome no default export
import * as CryptoJS from 'node_modules/crypto-js/crypto-js.js';

但是之后

console.log(CryptoJS.);

不提供AES /任何方法(我的编辑通常建议我可以通过自动完成使用哪些方法)

编辑2现在感谢Thierry和PierreDuc的贡献,很明显,打字和模块导入是无关联的概念.

但是他们都没有工作.这就是我所做的:

我下载了CryptoJS typings file,把它放在typings / cryptojs / cryptojs.d.ts中

然后我补充说

/// <reference path="cryptojs/cryptojs.d.ts"/>

到typings / main.d.ts

然后我在SystemJS的map配置中添加了cryptojs:

cryptojs: "node_modules/crypto-js/crypto-js.js"

最后我尝试在我的服务中导入cryptojs

import CryptoJS from 'cryptojs'

据我所知,有两个问题:

>因为当我尝试导入模块时没有自动完成(因为我还尝试重新启动Angular 2应用程序),所以没有加载打字.也许我不明白如何导入外部输入?
>无论如何都没有加载模块,我可以通过console.log(cryptojs)看到(没有打印,甚至没有定义;不太可能是我以前的尝试)

编辑3

最后我得到了导入工作,感谢Thierry和PierreDuc的建议(不知道第一个地方出了什么问题).
但是我仍然有打字问题.

尽管我放了

/// <reference path="../../typings/cryptojs/cryptojs.d.ts"/>

当我写作时,直接在我的服务中

import CryptoJS from 'cryptojs';

就在那条线下面,我没有自动完成功能,当我从npm start开始Angular 2应用程序时;我收到以下错误,应用程序无法启动

app/services/user.service.ts(6,22): error TS2307: Cannot find module 'cryptojs'.

注意:如果我将cryptojs添加到SystemJS配置(但不是a)然后写入(没有任何导入)

console.log(CryptoJS.AES.encrypt('my message','secret key123').toString());

它只是工作,但我宁愿解决打字输入问题.

您可以尝试这个,因为该库在您的主HTML文件中符合CommonJS:
System.config({
  map: {
    cryptojs: 'node_modules/crypto-js/crypto-js.js'
  },(...)
});

并以这种方式导入:

import CryptoJS from 'cryptojs';

对于编译部分,您可以遵循皮埃尔的建议.

编辑

我做了一些测试,这是方法.

>为crypto-js安装打字:

$typings install --ambient crypto-js

>在ts文件中包含相应的输入:

/// <reference path="../typings/main/ambient/crypto-js/crypto-js.d.ts"/>

import {Component} from 'angular2/core';
(...)

>在主HTML文件中配置SystemJS中的库:

<script>
  System.config({
    map: {
      'crypto-js': 'node_modules/crypto-js/crypto-js.js'
    },(...)
  });
</script>

>将库导入ts文件:

import CryptoJS from 'crypto-js';

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读