Import crypto-js in an angular 2 project (created with angular-cli)

穿精又带淫゛_ 提交于 2019-12-12 09:36:47

问题


I'm trying to import crypto-js in my angular2 project.

I followed several SO questions and also angular-cli guide, but at the end I still have the error Cannot find module 'crypto-js'

What I tried :

npm install crypto-js --save

and

typings install dt~crypto-js --global --save

then I modified the file angular-cli-build.js

var Angular2App = require('angular-cli/lib/broccoli/angular2-app');

module.exports = function(defaults) {
  return new Angular2App(defaults, {
    vendorNpmFiles: [
      'systemjs/dist/system-polyfills.js',
      'systemjs/dist/system.src.js',
      'zone.js/dist/**/*.+(js|js.map)',
      'es6-shim/es6-shim.js',
      'reflect-metadata/**/*.+(ts|js|js.map)',
      'rxjs/**/*.+(js|js.map)',
      '@angular/**/*.+(js|js.map)',
      'crypto-js/**/*.+(js|js.map)'
    ]
  });
};

and the file src/system-config.ts

const map: any = {
    'crypto-js': 'vendor/crypto-js'
};

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

After using

import * as CryptoJS from 'crypto-js';

I still have my error. Did I miss something ?

Thanks


回答1:


This may help you:
https://github.com/Uisli21/SecureAngularLogin


$ npm install crypto-js --save
$ npm install @types/crypto-js --save-dev

then:

import * as CryptoJS from 'crypto-js';

or

import CryptoJS = require('crypto-js');



回答2:


You can try following as a solution:

1. npm install --save @types/crypto-js


2. import { AES } from "crypto-js";


3. AES.encrypt('my message', 'secret key');



回答3:


Angular-cli still have some issues to integrate third-party plugins. So, Dont forget to add it in the index.html . Add like this way

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

I think it will solve your problem :)

Update

const map: any = {
    'crypto-js': 'vendor/crypto-js'
};



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



回答4:


Ok I got it. I just download the DefinitelyTyped file in typings/crypto-js/ and then I add the line /// <reference path="../../typings/crypto-js/crypto-js.d.ts" /> before importing CryptoJS.



来源:https://stackoverflow.com/questions/38479667/import-crypto-js-in-an-angular-2-project-created-with-angular-cli

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!