process.env.API_KEY 未定义

process.env.API_KEY is undefined

我正在使用 firebase 构建一个小型的反应应用程序。我试图将我的 firebase api 密钥 API_KEY=somekey 放在根文件夹中的 .env 文件中,但是当我使用 process.env.API_KEY 时,我在浏览器控制台中出现错误,如下图所示.

但是,我已经在 .env 中正确复制了我的 api-key。还有什么问题?

在使用 process.env.API_KEY 之前,是否需要在 package.json 中进行任何配置?

如果您正在使用 webpack,请尝试更改 webpack 配置。检查文档 here

const webpack = require("webpack");
const config = require("dotenv").config();

module.exports = {
  // some config
  plugins: [
    new webpack.EnvironmentPlugin(config.parsed),
  ],
};

您可以使用建议的步骤here

Your project can consume variables declared in your environment as if they were declared locally in your JS files. By default, you will have NODE_ENV defined for you, and any other environment variables starting with REACT_APP_.

嗨,这是解释如何在反应中使用环境变量的文档:link here

您必须将环境变量命名为 REACT_APP_API_KEY 才能在您的 React 项目中使用它。

您还可以查看此回复: .