Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

crypto.randomBytes is not a function in angular

Tags:

angular

I am importing ethereumjs-wallet in angular4,

import EthereumWallet from 'ethereumjs-wallet';
var wallet = EthereumWallet.generate();
const jsV3 = wallet.toV3(passwd);

the code inside the library shown as below

var privKey = crypto.randomBytes(32)

throws out an error

ERROR Error: Uncaught (in promise): TypeError: crypto.randomBytes is not a function TypeError: crypto.randomBytes is not a function TypeError: crypto.randomBytes is not a function at Function.webpackJsonp.../../../../ethereumjs-wallet/index.js.Wallet.generate

how to solve it ?

like image 974
user824624 Avatar asked Dec 09 '25 01:12

user824624


1 Answers

run

npm install crypto-browserify --save

and after, you need create a file to fix (workaround)... like this:

var fs = require('fs');

// PACKAGE_ERROR and FILE_ERROR is shown on your error
fs.readFile('./node_modules/[PACKAGE_ERROR]/[FILE_ERROR]', 'utf8', function (err,data) {
  if (err) return console.log(err);

  var result = data.replace('require(\'crypto\');', 'require(\'crypto-browserify\');');

  fs.writeFile('./node_modules/[PACKAGE_ERROR]/[FILE_ERROR]', result, 'utf8', function (err) {
     if (err) return console.log(err);
  });

});

Now, you need add the postinstall code on package.json

...
"scripts":{
"postinstall":"node [fixFileName].js",
...

And to finish, run:

npm install
ng serve OR ng build

I hope this helps!

like image 101
cdvillagra Avatar answered Dec 11 '25 21:12

cdvillagra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!