Hello, I’m using ionic 5 with angular 11, and all OK, but when try new angular 12 I found with a problem. some libraries give me this error:
Error: Module not found: Error: Can’t resolve ‘crypto’ …
Reading I have found this: → Error: Can't resolve 'crypto' in Angular 12 with Webpack 5 · Issue #908 · digitalbazaar/forge · GitHub
This errors came because webpack 5 (used at Angular 12) removed default browser polyfills. Install crypto-browserify (or library used) and add it as a resolve.fallback to your webpack.config.
In this site, said the solution is:
Add this to webpack.config.js
module.exports = {
resolve: {
fallback: {
crypto: require.resolve('crypto-browserify')
},
},
};
but the solution is to modify webpack.config.js and I don’t known how do it with Ionic.
Is there a reason you can’t just use the crypto in the browser?
Hello, rapropos. thank you for your answer.
I am not using ‘crypto’ directly in my code, it’s other third party libraries that use ‘crypto’.
Error example with lib ‘randomstring’ →
/node_modules/randomstring/lib/randomstring.js:3:13-30 - Error: Module not found: Error: Can’t resolve ‘crypto’) .
So I want to keep my code intact if possible.
From here: javascript - Module not found: Error: Can't resolve 'crypto' - Stack Overflow
I have try this two options, but not success:
1 → add this to package.json (If you don’t need crypto, I think I need it, but i will try it to see if compiled, but not success )
"devDependencies": {...},
"browser": { "crypto": false }
2 → Add this to tsconfig.json: (try it with node_modules/crypto-js and node_modules/crypto-browserify )
"compilerOptions": {
"baseUrl": "src",
"paths": {
.....,
"crypto": ["node_modules/crypto-js"]
}
Try it also with ‘node_modules/crypto-browserify’
but not success
I have found the solution:
I’m using Ionic Framework @ionic/angular 5.8.4 with @angular/cli 13.0.1
[javascript - Module not found: Error: Can't resolve 'crypto' - Stack Overflow](Solution here)
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"
],
...
}
BUT BE CAREFULL , my problem was into tsconfig.json because I have:
"compilerOptions": {
"baseUrl": "src",
So I need add “…/” to my path, then the correct modification into tsconfig.json is:
"compilerOptions": {
"baseUrl": "src",
"paths": {
.....
"crypto": ["../node_modules/crypto-js"]
}
Note ‘…/’ before ‘node_modules/crypto-js’
Now compile without problems…
What are you using randomstring
for? It should be trivial to swap that out for something that doesn’t need any crypto depedencies.
Hi, rapropos, randomstring was by speed when developing, now i am using my own function and uninstall randomstring.
But I’m still using realm-web ( https://docs.mongodb.com/realm/web/ ) to access atlas service , that still need crypto-js…