Web3js
找不到模組:錯誤:無法解析包括 web3 在內的 React 項目中的“流”
當我在項目中包含 web3 時,我會收到這樣的節點編譯錯誤……
ERROR in ./node_modules/cipher-base/index.js 3:16-43 Module not found: Error: Can't resolve 'stream' in '/Users/xxx/dev/blockchain/xxx-truffle-react/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 }
我收到這些包錯誤:
stream-browserify crypto-browserify stream-http https-browserify url/ os-browserify/browser
我已經使用成功添加了 web3
npm install web3
我還嘗試安裝每個麻煩的軟體包以及使用…
npm install crypto-browserify stream-browserify assert stream-http https-browserify os-browserify
這告訴我他們是最新的
我的 package-lock.json 的依賴項部分也有對它們的引用
"dependencies": { "@openzeppelin/contracts": "^4.5.0", "@testing-library/jest-dom": "^5.16.2", "@testing-library/react": "^12.1.4", "@testing-library/user-event": "^13.5.0", "assert": "^2.0.0", "crypto-browserify": "^3.12.0", "https-browserify": "^1.0.0", "os-browserify": "^0.3.0", "react": "^17.0.2", "react-dom": "^17.0.2", "react-scripts": "5.0.0", "stream-browserify": "^3.0.0", "stream-http": "^3.2.0", "web-vitals": "^2.1.4", "web3": "^1.7.1" }
經過一番研究,有人建議版本
react-scripts
需要為 4.0.3,所以我嘗試了一下,沒有任何區別。在我做任何大手術之前,比如
post-install
在依賴包中添加和更改程式碼來修復它,我希望我在做一些愚蠢的事情,並且有一個簡單的答案。
我相信將 react-scripts 更改為 4.0.3 並重新執行
yarn install
或npm install
會解決此問題。有幾種方法可以繞過它,但我喜歡這種方式,因為您不必彈出或降級。
我使用 react-app-rewired 做了一個解決方法。
- 將這些添加到您的 devDependencies 並執行
yarn/npm install
."devDependencies": { "assert": "^2.0.0", "buffer": "^6.0.3", "crypto-browserify": "^3.12.0", "https-browserify": "^1.0.0", "os-browserify": "^0.3.0", "process": "^0.11.10", "react-app-rewired": "^2.2.1", "stream-browserify": "^3.0.0", "stream-http": "^3.2.0", "url": "^0.11.0" }
- 更改 package.json 中的腳本以使用 react-app-rewired 執行:
"start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test", "eject": "react-app-rewired eject"
- 在您的根文件夾中創建一個
config.overrides.js
並將以下內容複製並粘貼到其中:const webpack = require("webpack"); module.exports = function override(config) { const fallback = config.resolve.fallback || {}; Object.assign(fallback, { crypto: require.resolve("crypto-browserify"), stream: require.resolve("stream-browserify"), assert: require.resolve("assert"), http: require.resolve("stream-http"), https: require.resolve("https-browserify"), os: require.resolve("os-browserify"), url: require.resolve("url"), }); config.resolve.fallback = fallback; config.plugins = (config.plugins || []).concat([ new webpack.ProvidePlugin({ process: "process/browser", Buffer: ["buffer", "Buffer"], }), ]); return config; };