Webpack/polyfill安装pact-lang-api后出现错误



当尝试连接react前端时,这是刚刚使用create-react-app创建的,在将pact-lang-api导入到应用程序后运行npm run start时,我得到了这个错误消息:

ERROR in ./node_modules/eventsource/lib/eventsource.js 5:12-28 Module not found: Error: Can't resolve 'https' in '/src/node_modules/eventsource/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: { "https": require.resolve("https-browserify") }'
install 'https-browserify' 
If you don't want to include a polyfill, you can use an empty module like this: resolve.fallback: { "https": false }
ERROR in ./node_modules/eventsource/lib/eventsource.js 7:11-26 Module not found: Error: Can't resolve 'http' in '/src/node_modules/eventsource/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: { "http": require.resolve("stream-http") }'
install 'stream-http' 
If you don't want to include a polyfill, you can use an empty module like this: resolve.fallback: { "http": false }
webpack compiled with 2 errors and 2 warnings

我的依赖项是这样的:

{
"@emotion/react": "^11.9.0",
"@emotion/styled": "^11.8.1",
"@mui/material": "^5.8.3",
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^13.5.0",
"pact-lang-api": "^4.3.3",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-scripts": "4.0.3",
"web-vitals": "^2.1.4"
}

我该如何解决这个问题?提前感谢任何帮助!

错误提示安装stream-httphttps-browserify

npm i stream-http https-browserify

刚刚修复了这个问题,我自己跟着https://alchemy.com/blog/how-to-polyfill-node-core-modules-in-webpack-5的解决方案。

请注意,本文的目标是解决web3.js包造成的这个问题,而不是pact-lang-api。对于pact-lang-api,您还需要添加url和util包,以便您的最终配置覆盖文件看起来像…

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"),
util: require.resolve("util"),
});
config.resolve.fallback = fallback;
config.plugins = (config.plugins || []).concat([
new webpack.ProvidePlugin({
process: "process/browser",
Buffer: ["buffer", "Buffer"],
}),
]);
return config;
};

本文中的解决方案不包括url: require.resolve("url")util: require.resolve("util"),但您将需要两者。

最新更新