【问题标题】:How to import non-core npm modules in Angular 2 e.g. (to use an encryption library)?如何在 Angular 2 中导入非核心 npm 模块,例如(使用加密库)?
【发布时间】:2016-08-14 20:07:09
【问题描述】:

在我的 Angular 2 应用程序(SystemJS 模块管理器,Typescript 作为脚本语言)中,我需要导入一个 npm 模块来处理加密(Crypto-JS;Forge-JS 或任何其他服务)

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

  <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 配置中实际添加什么,但我尝试过的解决方案都没有奏效。

编辑我也试过...

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

然后

 console.log(CryptoJS.); 

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

EDIT 2 现在感谢 Thierry 和 PierreDuc 的贡献,很明显类型和模块导入是未链接的概念。

但是它们都没有工作。这就是我所做的:

我下载了CryptoJS typings file,放到typings/cryptojs/cryptojs.d.ts中

然后我添加了

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

typings/main.d.ts

然后我在 SystemJS 的地图配置中添加了 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());

它只是工作,但我宁愿解决打字+导入问题。

【问题讨论】:

  • CryptoJS Definitely Typed 添加到您的打字,并将crypto-js.js 添加到您的index.html,您应该很高兴。不要忘记在引导文件中添加/// &lt;reference path="typings/cryptojs/cryptojs.d.ts"/&gt;
  • 到今天为止,这里的任何答案都适用于最新的 Angular 版本吗?

标签: encryption npm angular


【解决方案1】:

您可以试试这个,因为该库在您的主 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';
    

【讨论】:

  • 啊,是的,这样您就不必将其添加到您的index.html。我一直忘记这一点。但正如您所提到的,对于编译/代码提示,您需要 d.ts 文件。这不包括在node_module
  • “你必须”是什么意思? SystemJS 将正确导入所需的库,如果你将它放在 map 中。无需将其作为脚本添加到我认为的index.html。 (仅供参考,删除或添加引号(')到cryptojs的地图名称:))
  • 如果 SystemJS 配置是在 index.html 文件中定义的,您必须 ;-) 否则不... 感谢您指出错字!我更新了我的答案...
  • 但是我同意你的观点,你应该把这个配置外部化;-)
  • 再次感谢:现在它几乎可以完美运行了。唯一的问题是打字显然是错误的,因为 CryptoJS.AES(pars) 是有效的打字但不是有效的函数,而 CryptoJS.AES.encrypt(pars) 是有效的功能,但不是有效的类型。我会接受答案以感谢您的努力。也许你可以帮我解决最后一个问题,因为它基本上会阻止 Angular 应用程序在我重新启动时启动
【解决方案2】:

通过以下步骤/配置,我能够让 CryptoJS 在使用 angular-cli 生成的 Angular2 项目中工作:

重击

npm install crypto-js --save
typings install crypto-js --ambient --save

angular-cli-build.js

module.exports = function(defaults) {
  return new Angular2App(defaults, {
    vendorNpmFiles: [
      /* ... */
      'crypto-js/**/*.+(js|js.map)'
    ]
  });
};

system.config.ts

/** Map relative paths to URLs. */
const map: any = {
  'crypto-js': 'vendor/crypto-js'
};

/** User packages configuration. */
const packages: any = {
  'crypto-js': {
    defaultExtension: 'js',
    main: 'index.js',
    format: 'cjs'
  }
};

some.component.ts

import * as CryptoJS from 'crypto-js';

这是我唯一可以同时用于常规构建和-prod 构建的设置。我意识到这个问题并不是专门关于 angular-cli,但我想我还是会回答它,以防它帮助别人。

【讨论】:

  • 感谢您的回答。最后安装更新的类型(他们在我打开问题后修复它们)对我来说就像一个魅力
【解决方案3】:

答案会导入整个 crypto-js 库,因此如果您只使用其中的一小部分,应用就会变得臃肿。

我想让我的应用尽可能简洁,所以这是我的方法:

通过 NPM 安装

npm install core-js@3.1.6

systemjs.config.js

System.config({
    map:{
        'crypto-js':  'node_modules/crypto-js',
        ...
    },
    packages:{
        'crypto-js': {main: './index.js', defaultExtension: 'js', format: 'cjs'},
        ...
    }
});

component.ts

//only the core + the modules you need
import CryptoJS from 'crypto-js/core';
import 'crypto-js/sha1';

不过,这有几个缺点。快捷方式对我不起作用:

不起作用

let hash = CryptoJS.SHA1('abcdefghi'); // CryptoJS.SHA1 is undefined

有效

let sha1 = CryptoJS.algo.SHA1.create();
sha1.update("abcdefghi");
let hash = sha1.finalize();

为避免编译器错误"Could not find module x",我需要将以下内容添加到 custom.typings.d.ts

declare module 'crypto-js/core'

然后链接到我的 ma​​in.ts

中的类型
///<reference path="./app/custom.typings.d.ts"/>

主要缺点是其他答案中提到的类型似乎不适用于这种方法,因为它们适用于整个 crypto-js 库。例如,CryptoJS.algo 无法识别。所以它真的很糟糕,但我在 IDE 中没有智能感知/自动完成功能

那么为什么要设置这样的缺点呢?整个库向我的应用程序添加了大约 60kb 的缩小 JS,而仅导入我需要的内容会增加 4.5kb。这对我来说是一个胜利。

【讨论】:

    【解决方案4】:

    要安装cryptojs包运行以下命令:

    npm install crypto-js --save

    如果您使用的是 webpack/bundles 或更新的 angularjs 版本,则在完成上述安装后,请运行以下命令以获取声明文件。

    npm install --save @types/crypto-js

    在 node_modules 的@types 中将添加 d.ts 文件,以解决 cryptojs 的导入相关错误。这对我有用。

    【讨论】:

      【解决方案5】:

      当我尝试运行时:

      typings install --ambient crypto-js

      我得到了错误:

      打字错误!弃用“环境”标志已弃用。请改用“全局”

      相反,将此行放在 typings.json 文件中,它起作用了。

      "crypto-js": "registry:dt/crypto-js#3.1.4+20160505170201"

      【讨论】:

        猜你喜欢
        • 2017-05-24
        • 1970-01-01
        • 2017-02-14
        • 1970-01-01
        • 1970-01-01
        • 2020-06-30
        • 1970-01-01
        • 2021-09-12
        • 2016-03-23
        相关资源
        最近更新 更多