12

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?

eko
  • 39,722
  • 10
  • 72
  • 98
j809809jkdljfja
  • 767
  • 2
  • 9
  • 25

3 Answers3

3

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);
...
}
Javi
  • 345
  • 3
  • 7
2

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..
eko
  • 39,722
  • 10
  • 72
  • 98
  • 8
    But I think [crypto-js](https://www.npmjs.com/package/crypto-js) is a different module than [crypto](https://www.npmjs.com/package/crypto). – j809809jkdljfja Apr 11 '17 at 18:45
  • @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. – eko Apr 11 '17 at 18:49
  • thanks for the answers, but I still can't make it work: ERROR TypeError: crypto.createHmac is not a function – j809809jkdljfja Apr 11 '17 at 20:05
  • @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. – eko Apr 11 '17 at 20:07
1

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)

Acyuta
  • 19
  • 2