找不到模块:错误:无法解析“加密”

Ale*_*ers 5 node.js angularjs angular

错误信息:

重大更改:webpack < 5 默认情况下包含 Node.js 核心模块的 Polyfill。这已不再是这种情况。验证您是否需要此模块并为其配置一个polyfill。

所以我在谷歌上搜索这个问题并找到了很多解决方案。所以我想和大家分享一下:

  1. 首先,这种情况不仅可能发生在加密货币领域,也可能发生在 http、https、操作系统等其他领域。

  2. 检查数据包是否安装(本例已安装 crypto-browserify) 应该有一个文件夹 node_modules\crypto-browserify

如果不存在:npm install crypto browsrify,则yarn add @types/node@15.12.5 -D(对于此节点版本)

在node_modules\crypto-browserify中编辑package.json并添加

 , 
 "optionalDependencies": {},
 "browser": {
   "crypto": false
 },
Run Code Online (Sandbox Code Playgroud)

(在 devDependency 之后)

  1. 在 tsconfig.json 下添加
"compilerOptions": {
"paths":{
   "crypto":["node_modules/crypto-browserify"],
   "http":["node_modules/stream-http"],
   "https":["node_modules/https-browserify"]
   },
Run Code Online (Sandbox Code Playgroud)
  1. 在angluar.json下添加
"architect": {
   "build": {
   "builder": "@angular-devkit/build-angular:browser",
   "options": {
      "allowedCommonJsDependencies": ["crypto"],
      "allowedCommonJsDependencies": ["http"],
      "allowedCommonJsDependencies": ["https"],
Run Code Online (Sandbox Code Playgroud)

小智 1

我在 ReactJS 中使用 create-react-app(facebook) 遇到了这个问题

解决方案:

  1. 首先安装必要的软件包“crypto-browserify”

  2. 使用 create-react-app 修改reactjs中的webpack.config.js,该文件位于其中:

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

  • 搜索 module.exports 并在该函数内有一个返回:
module.exports = function (webpackEnv) {
  ...
  return {
   ...
    resolve: {
      ...
      fallback: {
        // Here paste
        crypto: require.resolve("crypto-browserify"),

      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

注意:可能需要更多包,例如“stream-browserify”,步骤是相同的​​。这个解决方案有效,但是当 webpack 项目启动时它会显示警告

Pd:我的母语不是英语,但我希望理解我。