j809809jkdljfja
j809809jkdljfja

Reputation: 807

How to use 'crypto' module in Angular2?

I install module:

npm install --save crypto

I import it to my component:

import { createHmac } from "crypto";

But I get error:

ERROR in -------------- (4,28): Canno t find module 'crypto'.

What am I doing wrong?

Upvotes: 13

Views: 29139

Answers (3)

Acyuta
Acyuta

Reputation: 19

The current tsconfig.json configuration (I'm using "typescript": "~3.5.3") includes a types compiler option that should be used in this case: In tsconfig.ts file add the following:

{
  "compilerOptions": {
    "types" : [ "node" ]
   }
}

Import the library where you want to use it with import crypto from 'crypto'

Don't use import * as crypto from 'crypto': it will import deprecated symbols/functions. (you should probably see the compiler complain about it)

Upvotes: 1

Javi
Javi

Reputation: 355

I am developing with the latest versions of Angular and 'crypto-js' seems to work fine.

Install the package and the definitions:

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

Use it:

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

Upvotes: 4

eko
eko

Reputation: 40677

You need to install the definition files for a 3rd party library like crypto. So that typescript can find the "meaning" for it.

I think the definition file is:

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

Then you can import the module like:

import * as crypto from "crypto";

If you can't find the definition file for that lib, you can write it on your own 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..

Upvotes: 2

Related Questions