关于reactjs:无法访问.env中的变量键(dotenv包React)

Can't access variable key inside .env (dotenv package React)

因此,我试图了解如何使用.env保护登录身份验证的api密钥和数据。 我已经遵循了dotenv软件包的过程和此处的stackoverflow答案。

我做了什么:

1.我安装了dotenv软件包

2.在我的根文件夹中,添加了一个只有一行的.env:

1
API_AUTH=http://myapilink.com

3.在我的App.js中,添加了以下行:

1
2
require('dotenv').config()
console.log(process.env.API_AUTH)

但是,console.log返回'undefined',为什么呢? 我错过了什么?


您必须在环境变量前面加上REACT_APP_。 看这里。

Note: You must create custom environment variables beginning with
REACT_APP_. Any other variables except NODE_ENV will be ignored to
avoid accidentally exposing a private key on the machine that could
have the same name. Changing any environment variables will require
you to restart the development server if it is running.

因此,不仅是API_AUTH,还可能是REACT_APP_API_AUTH

它将以process.env.REACT_APP_API_AUTH的形式显示在您的应用中。


Dotenv仅在服务器端工作。 它需要一个环境来存储变量。 在这里,我们提取.env文件的内容并将其简化为一个对象,然后将其传递到Webpack的DefinePlugin中,以允许我们稍后使用(process.env.API_AUTH):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const webpack = require('webpack');
const dotenv = require('dotenv');

module.exports = () => {
  const env = dotenv.config().parsed,
    envKeys = Object.keys(env).reduce((prev, next) => {
      prev[`process.env.${next}`] = JSON.stringify(env[next]);
      return prev;
    }, {});

  return {
    plugins: [
      new webpack.DefinePlugin(envKeys)
    ]
  };