109

I am getting the following list of errors when I run ng serve.

My package JSON is as follows:

{   "name": "ProName",   "version": "0.0.0",   "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"   },   "private": true,   "dependencies": {
    "@angular-devkit/build-angular": "~0.12.0",
    "@angular/animations": "5.2.10",
    "@angular/common": "5.2.10",
    "@angular/compiler": "5.2.10",
    "@angular/compiler-cli": "5.2.10",
    "@angular/core": "5.2.10",
    "@angular/forms": "5.2.10",
    "@angular/platform-browser": "5.2.10",
    "@angular/platform-browser-dynamic": "5.2.10",
    "@angular/router": "5.2.10",
    "@types/dotenv": "^4.0.3",
    "@types/errorhandler": "0.0.32",
    "@types/express": "^4.16.0",
    "@types/node": "^10.5.1",
    "apostille-library": "^7.1.0",
    "core-js": "^2.5.4",
    "dotenv": "^6.0.0",
    "errorhandler": "^1.5.0",
    "express": "^4.16.0",
    "nem2-sdk": "^0.9.7",
    "rxjs": "~6.3.3",
    "stream": "0.0.2",
    "tslib": "^1.9.0",
    "typescript": "^2.9.2",
    "zone.js": "~0.8.26"   } }

The error I get :

ERROR in ./node_modules/aws-sign2/index.js Module not found: Error: Can't resolve 'crypto' in '/Users/MYPC/Documents/Myproj/ProName/node_modules/aws-sign2' ERROR in ./node_modules/aws4/aws4.js Module not found: Error: Can't resolve 'crypto' in '/Users/MYPC/Documents/Myproj/ProName/node_modules/aws4' ERROR in ./node_modules/ecc-jsbn/index.js Module not found: Error: Can't resolve 'crypto' in '/Users/MYPC/Documents/Myproj/ProName/node_modules/ecc-jsbn' ERROR in ./node_modules/http-signature/lib/verify.js Module not found: Error: Can't resolve 'crypto' in '/Users/MYPC/Documents/Myproj/ProName/node_modules/http-signature/lib' ERROR in ./node_modules/http-signature/lib/signer.js Module not found: Error: Can't resolve 'crypto' in '/Users/MYPC/Documents/Myproj/ProName/node_modules/http-signature/lib' ERROR in ./node_modules/nem-sdk/build/external/nacl-fast.js Module not found: Error: Can't resolve 'crypto' in '/Users/MYPC/Documents/Myproj/ProName/node_modules/nem-sdk/build/external' ERROR in ./node_modules/nem-sdk/node_modules/aws-sign2/index.js

Illep
  • 16,375
  • 46
  • 171
  • 302

24 Answers24

154

I ran into a similar issue lately while trying to use another library (tiff.js) in a small project I was experimenting with.

The way I got around this was to add the following to my package.json file, right after the devDependencies section.

"devDependencies": {
    ...
},
"browser": {
    "crypto": false
}

This didn't seem to have any adverse effect when trying to use the library in the application.

R. Richards
  • 24,603
  • 10
  • 64
  • 64
  • 54
    The reason this happens is because when your run `ng serve`, it bundles up the dependencies you have in your `package.json` to serve it on the browser. However, `package.json` generally includes both server and browser dependencies, and any native module dependency (like `crypto`) cannot be bundled to serve on the browser. Setting `'crypto': false` in the `browser` section of `package.json` tells `ng serve` not to attempt to bundle that file. – asleepysamurai Jan 13 '19 at 06:33
  • 1
    You might have to stop and restart the "ng serve" operation to make this effective. Thanks, it worked. – Vibhor Dube Jun 16 '20 at 12:13
  • 8
    Great solution, unless you actually need to use the crypto library. – Fatih Oct 13 '20 at 11:10
  • what if you want to use the crypt library, then what would be the solution for the above? – LakShan Dec 08 '20 at 15:58
  • 16
    In my case I use webpack 5. I got a warning that explains why it happens and what to do: `BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default. This is no longer the case. Verify if you need this module and configure a polyfill for it. If you want to include a polyfill, you need to: - add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }' - install 'crypto-browserify' If you don't want to include a polyfill, you can use an empty module like this: resolve.fallback: { "crypto": false }` – MehranTM Feb 04 '21 at 20:41
  • 3
    There is now an ES modules version called "crypto-es". It clears these warnings. https://www.npmjs.com/package/crypto-es – Stewii Feb 19 '21 at 19:18
  • 19
    so where is resolve.fallback placed? angular.json in one of the tiers? – Mark May 14 '21 at 15:47
57

Adding this setting in tsconfig.json file under that project resolve this warning

"compilerOptions": {
"baseUrl": "./",
"paths": {
  "crypto": [
    "node_modules/crypto-js"
  ]
}
xinthose
  • 3,213
  • 3
  • 40
  • 59
Tarique Ahmed
  • 671
  • 5
  • 4
38

I like R. Richards's answer, but I thought it would be useful to provide some more information.

This is a known issue with Angular, and the Angular CLI dev team seems to think it's a feature rather than a bug. I, as well as other developers in this issue thread, disagree. Contributors to that thread provided several workaround fixes, but my project didn't compile successfully until I implemented R. Richards' solution. I didn't revert the previous changes, though, so tacnoman's and GrandSchtroumpf's fixes may be of use to others.

Some, like clovis1122 here and others in that issue thread, have questioned why a web app would need access to these libraries and why the necessary tasks can't be completed on the server side instead. I can't speak for everyone, but my use case is that, when authenticating a user account, Strapi responds with a JSON Web Token string that must be decoded by the client. Since the necessary library depends on crypto and stream, you won't be able to extract the JWT expiration time unless those dependencies are available.

In case anyone has trouble extrapolating from R. Richards' answer, you'll have to set to false any dependencies that are showing up in "can't resolve x" errors. For example, the critical part of my package.json is:

    "browser": {
        "crypto": false,
        "stream": false
    }
Joseph Collins
  • 431
  • 5
  • 7
28

I thought I would expand on what Tarique Ahmed wrote in his answer.

I was using an npm module that had the following line in the code:

const crypto = require('crypto');

I couldn't add:

"browser": {
  "crypto": false
}

to the package.json because the crypto package had to be part of the build.

It turns out that during the compilation process Angular seems to have decided to install the crypto-browserify package instead of crypto.

Adding the following to the tsconfig.json file instructs the build to use the crypto-browserify library every time that crypto is required. As you can see, I had the same issue for the stream package.

"paths": {
  "crypto": [
    "node_modules/crypto-browserify"
  ],
  "stream": [
    "node_modules/stream-browserify"
  ]
}
lemming
  • 1,753
  • 14
  • 12
  • This is the most clear and precise solution provided. Just installed and used `crypto-browserify` instead of `crypto` and made *tsconifg.json* as mentioned above. – Bopsi Nov 03 '21 at 14:59
19

If you upgraded to Webpack 5, you need to add this to your webpack config file:

resolve: {
    fallback: { crypto: false },
},
Luca Fagioli
  • 12,722
  • 5
  • 59
  • 57
  • 1
    +1 This works as current angular 12, `node: { crypto: false } ` is deprecated. You need to merge a webpack.config.ts with @angular-builders/custom-webpack – sdykae Jun 28 '21 at 07:23
  • 2
    @LucaFagioli I've been seen this solution but I don't have a webpack config or at least I don't see it – Ricardo Sanchez Santos Jul 08 '21 at 17:45
  • @RicardoSanchezSantos Webpack can actually work without a configuration file. You need to create one. Check [this page](https://webpack.js.org/configuration/) for support. – Luca Fagioli Jul 12 '21 at 12:06
  • List of polyfills you can use to fix this - https://webpack.js.org/configuration/resolve/ – Nicholas Zozaya May 02 '22 at 05:14
18

After having the same issue with Angular 11 and crypto-js 4 (and manually setting the path in tsconfig.json), I found rolling back crypto-js to version 3.1.9-1 fixed the issue. It seems a change made in version 4 caused the issue.

npm install crypto-js@3.1.9-1

Explained here in repo issues:

GitHub issue

OllyBarca
  • 1,501
  • 1
  • 18
  • 35
  • I had the same issue and it works for me. I work with Angular 11 and I had installed the 4.0 crypto version. –  May 16 '21 at 09:14
  • I had the same issue with Angular 11 and I had crypto-js verion 4.0. I confirm that this is the solution for that case. – lord5et Oct 07 '21 at 07:49
3

My Error

enter image description here

In my Case the import { get } from "express/lib/response" is the culprit, which is automatically added by vs-code. So, after removing it I solved my issue

enter image description here

shubhamjr
  • 129
  • 9
2

aws-sign2 is a NodeJS package (and crypto is a NodeJS module), but it looks like you're dealing with a web application. It makes sense that the crypto module is not available in that environment.

Would it be possible to complete what you need to do server-side? Otherwise, you may need to look for another package.

clovis1122
  • 672
  • 8
  • 12
2

For Laravel Inertia JS project, my solution was:

1- Add dependencies to package.json

   "dependencies": {
        "crypto-browserify": "3.12.0",
        "crypto-random-string": "^3.3.0",
        "stream": "^0.0.2"
    }

2-In webpack.config.js:

const path = require('path');

module.exports = {
    resolve: {
        alias: {
            '@': path.resolve('resources/js'),
        },
        fallback: {
            crypto: require.resolve('crypto-browserify'),
            stream: require.resolve('stream'),
        },
    },
};

3-Install, build and run:

npm install && npm run watch
Maximiliano Sosa
  • 388
  • 1
  • 7
  • 18
2

I have resolved my issue using below steps:

Add below to tsconfig.json to resolve crypto warning:

"paths": {
      "crypto": [
        "node_modules/crypto-js"
      ]
    },

and add below to angular.json

"options": {
"allowedCommonJsDependencies": [
              "crypto-js"
            ],
...
}
2

crypto is a Node.js module hence it wouldn't work on Angular. I'm sure there might be an alternative way or you can use Node.js with Angular. crypto module will work on Node.js.

Dave Lee
  • 316
  • 3
  • 9
1

Using direct import may not work with ES6 Enviornment..

This may help you.

$ npm i crypto-js@latest // For using latest version 4

import AES from 'crypto-js/aes';
import Utf8 from 'crypto-js/enc-utf8';
import { secretKey } from './environments/environment';

/** Encryption */
const data = {key: 'Test Value'};
const ciphertext = AES.encrypt(JSON.stringify(data), secretKey).toString();
console.log('Encrypted Data', ciphertext);

/** Decryption */
const bytes = AES.decrypt(ciphertext, secretKey);
const decryptedData = JSON.parse(bytes.toString(Utf8));
console.log('Decrypted Data', decryptedData);

https://github.com/brix/crypto-js/issues/168#issuecomment-785617218

1

When using #Laravel framework with Laravel Mix this is going to be more trick. I spend some hours on this NPM nightmare and found a solid solution.

So, in your webpack.mix.js you find the 'comment'

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

Now just below that comment add the following lines;

mix.webpackConfig(webpack => {
    return {
        plugins: [
            new webpack.LoaderOptionsPlugin({
                exports: {
                    resolve: {
                        fallback: {
                            crypto: require.resolve('crypto-browserify'),
                        }
                    }
                }
            })
        ]
    };
});

Now you can use Laravel Mix just like you would edit webpack.config.js ;) Also; In package.json remove:

--no-progress --hide-modules

These are no longer valid for WebPack >= 5. Enjoy!

Digital Human
  • 1,599
  • 1
  • 16
  • 26
0

After a deep a research i found that the solution is very simple: replace import * as CryptoJS from 'crypto-js'; with declare var CryptoJS;

Dawoods
  • 9
  • 1
0

Add the option allowedCommonJsDependencies with literal "crypto-js" in a array, this in file angular.json:

"architect": 
        "build": {              
          "options": {               
            "allowedCommonJsDependencies": [
              "crypto-js"
            ]
          },
         }
 }

This will disable all warnings, tested in Angular 11.

Yigo
  • 1
0

My problem was that I was trying to build to node and web using the same code, but is not possible to built to web while importing a WebSocket dependency, ws in my case

So the solution is by using a wrapper:

Install a wrapper, I will use isomorphic-ws because is made for ws

npm i --save isomorphic-ws

Remove const WebSocket = require('ws')

Replace with:

const WebSocket = require('isomorphic-ws')
Rodrigo João Bertotti
  • 5,179
  • 2
  • 23
  • 34
0

I ended up going into

node_modules/react-scripts/config/webpack.config.js

and adding:

fallback: {
        // Here paste
        crypto: require.resolve("crypto-browserify"),
        https: require.resolve("https-browserify"),
        http: require.resolve("stream-http"),
        url : require.resolve("url")
      }

And now my react app builds with errors but no dependency issues. Ill update this when I get it building.

Jon Gan
  • 29
  • 5
0

Add

npm install crypto-js

Or Add a specific version according to your project need

npm install crypto-js@4.0.0

Also, run the above commands in Window "run as administrator" or in Linux use sudo

paul
  • 519
  • 6
  • 13
0

Alot of answers already but still none of them works. In my case I see warning message


BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default. This is no longer the case. Verify if you need this module and configure a polyfill for it.  If you want to include a polyfill, you need to:         - add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'         - install 'crypto-browserify' If you don't want to include a polyfill, you can use an empty module like this:         resolve.fallback: { "crypto": false }

comment from @stewii did helped me to resolved this.

There is now an ES modules version called "crypto-es". It clears these warnings. npmjs.com/package/crypto-es

After this I imported cryptoES

import CryptoES from 'crypto-es';

and remove the existing import of cryptoJs. Re-start the compile and Voila.. The warning message is gone.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Santosh
  • 3,477
  • 5
  • 37
  • 75
0

I tried a lot of the solutions above but the final thing that worked for me was downloading the crypto-es package and adding, "type":"module" to package.json.

https://www.npmjs.com/package/crypto-es

brohjoe
  • 854
  • 4
  • 17
  • 39
0

I was facing same issue, Just run node patch.js and it worked. The issue is, browser doesn't allow server files to be run on browser. In case you need some of these, You can use node patch.js. If you don't want to run any server file on browser, you can simply apply above mentioned solution by @R.Richards. Might be helpful for someone..

Analyst
  • 751
  • 6
  • 15
0

In my case, the solution described by R.Richards doesn't work. However, following several threads along this issue, I finally understood where to insert the recommendation provided in the warning message and solved this warning.

WARNING in ./node_modules/bcryptjs/dist/bcrypt.js 64:13-45
Module not found: Error: Can't resolve 'crypto' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\bcryptjs\dist'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

**If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
        - install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "crypto": false }**

Differently from many contributors, I didn't want to install crypto-browserify as I don't need it (*), and I chose to add the fallback { "crypto": false }. However I didn't know where to add this fallback. After reading several threads, I found it was in the webpack.config.js file, which is located in the directory node_modules/react_scripts/config. Adding this fallback made the compilation succeed without any warning.

(*) PS : I once tried to add the following fallback { "crypto": require.resolve("crypto-browserify") }, but it led to generation of 7 errors, requiring other modules :

    Failed to compile.

Module not found: Error: Can't resolve 'stream' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\cipher-base'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
        - install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "stream": false }
ERROR in ./node_modules/cipher-base/index.js 2:16-43
Module not found: Error: Can't resolve 'stream' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\cipher-base'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
        - install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "stream": false }

ERROR in ./node_modules/readable-stream/lib/_stream_readable.js 43:13-37
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\readable-stream\lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
        - install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "buffer": false }

ERROR in ./node_modules/readable-stream/lib/_stream_writable.js 65:13-37
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\readable-stream\lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
        - install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "buffer": false }

ERROR in ./node_modules/readable-stream/lib/internal/streams/buffer_list.js 63:15-32
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\readable-stream\lib\internal\streams'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
        - install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "buffer": false }

ERROR in ./node_modules/ripemd160/index.js 3:13-37
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\ripemd160'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
        - install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "buffer": false }

ERROR in ./node_modules/safe-buffer/index.js 3:13-30
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\safe-buffer'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
        - install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "buffer": false }

ERROR in ./node_modules/safer-buffer/safer.js 5:13-30
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\safer-buffer'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
        - install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "buffer": false }

webpack compiled with 7 errors
0

QUASAR FRAMEWORK v2

Just in case you are using Quasar v2, the working solution is to just update the quasar.config.js build :

module.exports = configure(function (ctx) {
  build: {
      chainWebpack (chain) {
          const nodePolyfillWebpackPlugin = require('node-polyfill-webpack-plugin')
          chain.plugin('node-polyfill').use(nodePolyfillWebpackPlugin)
          chain.resolve.alias.set('crypto', require.resolve('crypto-browserify'))

       }
   
})
Reamon S.
  • 318
  • 3
  • 8
-3

I had this problem in ReactJS with create-react-app(facebook)

Solution:

  1. First install the necessary packages "crypto-browserify"

  2. Modify webpack.config.js in reactjs with create-react-app this file is inside:

node_modules/react-scripts/config/webpack.config.js

  • Search module.exports and inside this function there is a return:
module.exports = function (webpackEnv) {
  ...
  return {
   ...
    resolve: {
      ...
      fallback: {
        // Here paste
        crypto: require.resolve("crypto-browserify"),

      }
    }
  }
}

Note: Is possible you need other packages how "stream-browserify" the steps are same. This solution works, but when the webpack project starts it shows warnings

Pd: I am not native speaker English, but I hope understand me.

Camilo Gomez
  • 165
  • 1
  • 6