将 .env 文件添加到 React 项目 [英] Adding an .env file to React Project

查看:22
本文介绍了将 .env 文件添加到 React 项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我提交到 github 时,我试图隐藏我的 API 密钥,并且我已经浏览了论坛以获得指导,尤其是以下帖子:

I'm trying to hide my API Key for when I commit to github, and I've looked through the forum for guidance, especially the following post:

如何在创建时隐藏 API 密钥-反应应用程序?

我进行了更改并重新启动了纱线.我不确定自己做错了什么——我在项目的根目录中添加了一个 .env 文件(我将其命名为 process.env)并在文件我只是把REACT_APP_API_KEY = 'my-secret-api-key'.

I made the changes and restarted yarn. I'm not sure what I'm doing wrong––I added an .env file to the root of my project (I named it process.env) and in the file I just put REACT_APP_API_KEY = 'my-secret-api-key'.

我想这可能是我在 App.js 中向 fetch 添加密钥的方式,并且我尝试了多种格式,包括不使用模板文字,但是我的项目仍然无法编译.

I'm thinking it might be the way I'm adding the key to my fetch in App.js, and I've tried multiple formats, including without using the template literal, but my project will still not compile.

非常感谢任何帮助.

performSearch = (query = 'germany') => {
    fetch(`https://api.unsplash.com/search/photos?query=${query}&client_id=${REACT_APP_API_KEY}`)
    .then(response => response.json())
    .then(responseData => {
        this.setState({
            results: responseData.results,
            loading: false
        });
     })
     .catch(error => {
            console.log('Error fetching and parsing data', error);
     });
}

推荐答案

4个步骤

  1. npm install dotenv --save

接下来将以下行添加到您的应用中.

Next add the following line to your app.

require('dotenv').config()

然后在您的应用程序的根目录创建一个 .env 文件并将变量添加到其中.

Then create a .env file at the root directory of your application and add the variables to it.

// contents of .env 

REACT_APP_API_KEY = 'my-secret-api-key'

  1. 最后,将 .env 添加到您的 .gitignore 文件中,以便 Git 忽略它并且它永远不会在 GitHub 上结束.
  1. Finally, add .env to your .gitignore file so that Git ignores it and it never ends up on GitHub.

如果您使用的是 create-react-app 那么您只需要第 3 步和4 但请记住变量需要以 REACT_APP_ 开头才能工作.

If you are using create-react-app then you only need step 3 and 4 but keep in mind variable needs to start with REACT_APP_ for it to work.

参考:https://create-react-app.dev/docs/adding-custom-environment-variables/

注意 - 在 .env 文件中添加变量后需要重新启动应用程序.

参考 - https://medium.com/@thejasonfile/using-dotenv-package-to-create-environment-variables-33da4ac4ea8f

这篇关于将 .env 文件添加到 React 项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆