简体   繁体   English

环境变量在 React 应用程序中不起作用

[英]Environment variables are not working in React app

I'm currently working with a 3rd party API, which has an API key.我目前正在使用具有 API 密钥的 3rd 方 API。 I am intending to store it in a .env file and have been doing it but it always comes up as undefined when I try to access it with process.env .我打算将它存储在.env文件中并且一直在这样做,但是当我尝试使用process.env访问它时,它总是显示为undefined

My .env file is keys.env which is outside of the src directory of my React JS app.我的.env文件是keys.env ,它在我的React JS应用程序的src目录之外。 I have restarted my development server, cleaned the cache of npm but my React JS app does not recognize the .env variable at all.我重新启动了我的开发服务器,清除了npm的缓存,但我的React JS应用程序根本无法识别.env变量。

My File Structure:我的文件结构:

|-node_modules<br>
|-public<br>
|-src<br>
|  .gitignore<br>
|  keys.env<br>
|  package-lock.json<br>
|  package.json <br>

My keys.env file:我的keys.env文件:

REACT_APP_TEST_KEY=somekey

How the .env variable is accessed:如何访问.env变量:

process.env.REACT_APP_TEST_KEY

Output:输出:

undefined

I think you need config webpack file to use keys.env because the file name default of environment is .env我认为你需要配置webpack文件来使用 keys.env 因为环境的文件名默认是.env

// webpack.config.js
const Dotenv = require('dotenv-webpack');
 
module.exports = {
  ...
  plugins: [
    new Dotenv({
        path: './some.other.env' // default is .env
    })
  ]
  ...
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM