How to use 'crypto' module in Angular2?
Solution 1
To use crypto
NodeJS library with Typescript (Angular >= 2 for example) follow these steps:
-
npm install @types/node --save-dev
to install NodeJS definitions -
In
tsconfig.ts
file add the following:"files": [ "./node_modules/@types/node/index.d.ts" ]
Import the library where you want to use it with
import * as crypto from 'crypto';
Solution 2
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);
...
}
Solution 3
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..
Related videos on Youtube
j809809jkdljfja
Updated on June 04, 2022Comments
-
j809809jkdljfja almost 2 years
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?
-
j809809jkdljfja about 7 years
-
eko about 7 years@johnerfx ah thanks for the feedback, you can declare the module as any or create its definition file on your own. I'll edit my answer with an example.
-
j809809jkdljfja about 7 yearsthanks for the answers, but I still can't make it work: ERROR TypeError: crypto.createHmac is not a function
-
eko about 7 years@johnerfx if you are using systemjs did you include it in your imports? or your index.html? or if you are using angular-cli did you include it in your scripts? I got to go now but I will check it again in the morning.
-
Kriil almost 5 yearsGENIUS! This adds the built-in crypto library from node.js, which actually has the createHmac function. npmjs.com/package/crypto
-
Kriil almost 5 yearsI spoke too soon. It doesn't seem to work for Angular 7.. the import doesn't work. Cannot find module 'crypto'