.env 变量在 React JS 应用程序中返回未定义

Jus*_*aya 3 javascript powershell environment-variables reactjs dotenv

我正在研究这个反应应用程序并考虑在里面添加一些环境变量,这就是我所做的:

  1. 安装了最新版本的 react-scripts
  2. 在根文件夹中添加了 .env 文件(与 node_modules 文件夹所在的位置相同)
  3. 添加 REACT_APP_OTHER_OTHER_THING=asdfas 只是为了测试变量
REACT_APP_OTHER_OTHER_THING=asdfas
Run Code Online (Sandbox Code Playgroud)
  1. 打开里面的 index.js 和 console.log(process.env.REACT_APP_OTHER_OTHER_THING) 查看输出
import React from 'react';
import Reactdom from 'react-dom';
import App from './App';

console.log(process.env.REACT_APP_OTHER_OTHER_THING, 'DOTENV')

Reactdom.render(<App/>, document.getElementById("app"))
Run Code Online (Sandbox Code Playgroud)

然后我重建了应用程序并启动了应用程序以查看结果,但随后它给出了 undefined 作为 process.env.REACT_APP_OTHER_OTHER_THING 的输出。然后我尝试打印 process.env.NODE_ENV (它正在工作并打印“development”作为输出)。

注意:我还尝试添加临时变量,如文档在https://create-react-app.dev/docs/adding-custom-environment-variables >> 重建服务器并运行($env:REACT_APP_OTHER_OTHER_THING= " abcdef") -and (npm start) << 因为我在 powershell 上运行它仍然给出 undefined 作为输出。

我能做些什么吗?谢谢你

Jus*_*aya 5

Alright, the problem I'm having seemed to be from the webpack I made in my React App,

I tried to follow the instruction from this article and it's working well!

after configuring my webpack, I rebuilt it, restart the server, and it works!

edit: for my solution, I added:

const dotenv = require('dotenv');

const env = dotenv.config().parsed;

const envKeys = Object.keys(env).reduce((prev, next) => {
    prev[`process.env.${next}`] = JSON.stringify(env[next]);
    return prev; }, {});
Run Code Online (Sandbox Code Playgroud)

at the top of webpack.common.js

and also added

    plugins: [
        new webpack.DefinePlugin(envKeys), //this line
    ]
Run Code Online (Sandbox Code Playgroud)

in the module.exports in the plugin. I hope this helps! :)

  • 最好添加文章的相关部分,以防万一网址有一天会失效 (3认同)

Dee*_*bug 5

确保它具有正确的目录树

D:\your-react-project\.env

  • 这里可能是your-react-project \ .env.development

它应该位于默认 README.md 放置的路径中