在我的Angular 2应用程序(SystemJS模块管理器,Typescript作为脚本语言)中,我需要导入一个npm模块来处理加密(Crypto-JS; Forge-JS或任何其他用于此目的的加密)
对于 CryptoJS ,通过 npm安装后,请安装 *我尝试通过添加:
<script src="node_modules/crypto-js/crypto-js.js"></script>
在索引中: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 config 中实际输入的内容,但是我尝试过的解决方案均无效。
编辑我也尝试过...
// 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,并将其放在types/cryptojs/cryptojs.d.ts中
然后我加了
/// <reference path="cryptojs/cryptojs.d.ts"/>
到打字/main.d.ts
然后我在SystemJS的 map 配置中添加了cryptojs:
cryptojs: "node_modules/crypto-js/crypto-js.js"
最后,我尝试通过以下方式在服务中导入cryptojs:
import CryptoJS from 'cryptojs'
据我所知有两个问题:
由于尝试导入模块时没有自动完成功能,因此未加载
编辑3
最后,感谢Thierry和PierreDuc的建议,我终于开始了导入工作(不确定到底是哪里出了问题)。
但是我仍然有打字方面的问题。
尽管我把
/// <reference path="../../typings/cryptojs/cryptojs.d.ts"/>
当我写信时,直接在我的服务中
import CryptoJS from 'cryptojs';
在该行的下面,我没有自动补全功能,当我通过启动Angular 2应用时,npm start ;我收到以下错误,应用无法启动
app/services/user.service.ts(6,22): error TS2307: Cannot find module 'cryptojs'.
注意:如果我将cryptojs添加到SystemJS配置中(而不是添加),然后写入(不进行任何导入)
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';
对于编译部分,您可以遵循Pierre的建议。
编辑
我做了一些测试,这就是方法。
$ typings install --ambient crypto-js
/// <reference path="../typings/main/ambient/crypto-js/crypto-js.d.ts"/>
import {Component} from 'angular2/core';
(...)
<script>
System.config({
map: {
'crypto-js': 'node_modules/crypto-js/crypto-js.js'
},
(...)
});
</script>
import CryptoJS from 'crypto-js';