首页 > 解决方案 > 如何在没有 Webpack 的情况下将 Dotenv 与 react-scripts 一起使用

问题描述

我正在从下面的 repo 中探索这个 React 项目,并且 process.env 没有返回任何值(当我控制台记录它们时未定义)。这些变量在根目录创建的 .env.local 文件中声明,根据 repo 的说明,所有的前缀都是 REACT_APP_ 不涉及 webpack。它使用 react-scripts 来加载 yarn start。谁能告诉它为什么不起作用?

git 克隆https://github.com/figment-networks/learn-solana-dapp

谢谢:)

标签: reactjsenvironment-variablesdotenvreact-scripts

解决方案


您可以尝试不先配置 dotenv,通过重命名.env.example.env.local以下任何链接名称,因为我相信这是使用创建的create-react-app(因为存在react-scripts

https://create-react-app.dev/docs/adding-custom-environment-variables/#what-other-env-files-can-be-used

虽然它安装了 dotenv,但它似乎没有使用它,使用它可以执行以下操作:

将其添加到 src 中 index.js 的开头:

import path from 'path';
import dotenv from 'dotenv';
dotenv.config({ path: path.join(__dirname, '../.env.example') });

必须配置 dotenv 才能使用它的变量,但在下面不需要create-react-app


推荐阅读