我的 React 应用程序中不断出现此错误
Compiled with problems: X
ERROR in ./ node_modules / dotenv / lib / main.js 1: 11 - 24
Module not found: Error: Can't resolve 'fs' in 'C: \Users\USER\Desktop\dapps\nefty\node_modules\dotenv\lib'
ERROR in ./ node_modules / dotenv / lib / main.js 3: 13 - 28
Module not found: Error: Can't resolve 'path' in 'C: \Users\USER\Desktop\dapps\nefty\node_modules\dotenv\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: { "path": require.resolve("path-browserify") }'
- install 'path-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "path": false }
ERROR in ./ node_modules / dotenv / lib / main.js 5: 11 - 24
Module not found: Error: Can't resolve 'os' in 'C: \Users\USER\Desktop\dapps\nefty\node_modules\dotenv\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: { "os": require.resolve("os-browserify/browser") }'
- install 'os-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "os": false }
我尝试按照创建 webpack.config.js 提供的说明并添加后备,如下所示
module.exports = {
resolve: {
fallback: { "path": require.resolve("path-browserify") },
},
}
没有区别。我在他们的 github 上检查了类似的问题页面,找不到有效的修复(大多数是强调问题的评论,甚至没有指出合理的工作解决方案)
最佳答案
感谢@user3133,我能够理解真正的问题。看来 dotenv 应该只用在像 nodejs 这样的后端应用程序中,而不应该用在像 react 这样的前端应用程序中。
当错误出现时,并没有指出错误的来源,所以我基本上是“迷失在暴风雪中”。我能够弄清楚错误来自于 src
目录中的引用 dotenv,该目录是 react
的域,您的所有 React 代码都在海外。
所以基本上我能够通过删除 src 目录中引用 dotenv
的所有代码行来解决这个问题,例如:
require('dotenv').config();
注意,放在src目录之外的任何地方都可以。
有趣的事实:react 有它自己的 dotenv,你只需将 REACT_APP_
放在你的环境变量前面就可以访问它。
关于reactjs - 使用 create-react-app react-scripts 的 Dotenv 问题/错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71019949/