How to use the 'crypto' module in Angular2?

I am installing the module:

npm install --save crypto

      

I am importing it into my component:

import { createHmac } from "crypto";

      

But I am getting error:

ERROR in -------------- (4.28): Canno t find module 'crypto'.

What am I doing wrong?

+6


source to share


3 answers


You need to install definition files for a third party library eg crypto

. So typescript can find a "value" for it.

I think the definition file:

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

      

Then you can import the module like this:

import * as crypto from "crypto";

      



If you can't find a definition file for this lib, you can write it yourself or as a workaround, you can declare the module as any

, but typescript won't be able to auto-complete the methods.

declare var crypto: any;

      

and use its methods like:

crypto.createHmac..

      

+5


source


To use crypto

NodeJS library with Typescript (like Angular> = 2) follow these steps:



  1. npm install @types/node --save-dev

    to install NodeJS definitions
  2. tsconfig.ts

    Add the following to the file :

    "files": [ "./node_modules/@types/node/index.d.ts" ]

  3. Import the library where you want to use it with import * as crypto from 'crypto';

+1


source


I am working with the latest Angular versions and crypto-js seems to be working fine.

Install package and definitions:

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

      

Use this:

import { SHA256, enc } from "crypto-js";
...
login() {
...
   const hashedPass = SHA256(this.loginForm.value.password).toString(enc.Hex);
...
}

      

+1


source







All Articles