且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-22 18:18:52

你可以试试这个,因为你的主 HTML 文件中的库是 CommonJS 兼容的:

You could try this since the library is CommonJS-compliant in your main HTML file:

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

并以这种方式导入:

import CryptoJS from 'cryptojs';

编译部分可以参考皮埃尔的建议.

For the compilation part, you can follow the Pierre's suggestion.

编辑

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

I made some tests and here is the way to do.

  • 为 crypto-js 安装类型:

  • Install typings for crypto-js:

$ typings install --ambient crypto-js

  • 在您的 ts 文件中包含相应的类型:

  • Include the corresponding typings into your ts file:

    /// <reference path="../typings/main/ambient/crypto-js/crypto-js.d.ts"/>
    
    import {Component} from 'angular2/core';
    (...)
    

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

  • Configure the library in SystemJS in your main HTML file:

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

  • 将库导入您的 ts 文件:

  • Import the library into your ts files:

    import CryptoJS from 'crypto-js';