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

问题描述

限时删除!!

当我提交到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:

如何在create- react-app?

我进行了更改并重新启动了纱线.我不确定自己在做什么错–我在项目的根目录中添加了.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

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

2) Next add the following line to your app.

require('dotenv').config()

3)然后在应用程序的根目录中创建一个.env文件,并向其中添加变量.

3)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'

4)最后,将.env添加到您的.gitignore文件中,以便Git忽略它,并且它永远不会在GitHub上出现.

4)Finally, add .env to your .gitignore file so that Git ignores it and it never ends up on GitHub.

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

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

1403页,肝出来的..

09-06 12:10