reactjs - 使用 create-react-app react-scripts 的 Dotenv 问题/错误

标签 reactjs webpack create-react-app dotenv react-scripts

我的 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_ 放在你的环境变量前面就可以访问它。

在这里阅读更多:Is it possible to use dotenv in a react project?

关于reactjs - 使用 create-react-app react-scripts 的 Dotenv 问题/错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71019949/

相关文章:

javascript - 根据传递的输入过滤对象数组 : Javascript

html - 在React中有条件地添加表n+1表行(<tr>)

javascript - yarn 工作区和 lerna 导致无效的 Hook 调用

node.js - Heroku 上的 413(请求实体太大)带有 Node.JS 和 Create-React-App BuildPack

javascript - 我可以发送多个有关不断变化的操作的事件吗?

javascript - 设置部署路由

webpack - webpack-删除 “webpackBootstrap”代码

javascript - Webpack 可变命名 require

reactjs - 在另一个 webpack 项目中使用带有 React hooks 的 webpack 项目会导致错误

reactjs - 为什么 create-react-app 在尝试 eslint 时会给出 typescript 错误(尽管没有 typescript 文件)?