reactjs 将 .env 文件添加到 React 项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49579028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:30:29  来源:igfitidea点击:

Adding an .env file to React Project

reactjsenvironment-variablesapi-key

提问by Bianca M

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:

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

How do I hide API key in create-react-app?

如何在 create-react-app 中隐藏 API 密钥?

I made the changes and restarted yarn. I'm not sure what I'm doing wrong––I added an .envfile 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'.

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

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

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

Any help is much appreciated.

任何帮助深表感谢。

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);
     });
}

回答by T04435

So I'm myself new to React and I found a way to do it.

所以我自己是 React 的新手,我找到了一种方法。

This solution does not requireany extra packages.

此解决方案不需要任何额外的包。

Step 1 ReactDocs

步骤 1 ReactDocs

In the above docs they mention export in Shell and other options, the one I'll attempt to explain is using .envfile

在上面的文档中,他们提到了在 Shell 中导出和其他选项,我将尝试解释的是使用.env文件

1.1 create Root/.env

1.1 创建Root/.env

#.env file
REACT_APP_SECRET_NAME=secretvaluehere123

Important notes it MUSTstart with REACT_APP_

重要说明它必须REACT_APP_ 开头

1.2 Access ENV variable

1.2 访问 ENV 变量

#App.js file or the file you need to access ENV
<p>print env secret to HTML</p>
<pre>{process.env.REACT_APP_SECRET_NAME}</pre>

handleFetchData() { // access in API call
  fetch(`https://awesome.api.io?api-key=${process.env.REACT_APP_SECRET_NAME}`)
    .then((res) => res.json())
    .then((data) => console.log(data))
}

1.3 Build Env Issue

1.3 构建环境问题

So after I did step 1.1|2 it was not working, then I found the above issue/solution. React read/creates env when is built so you need to npm run startevery time you modify the .env file so the variables get updated.

因此,在我执行步骤 1.1|2 后它不起作用,然后我找到了上述问题/解决方案。React 会在构建时读取/创建 env,因此每次修改 .env 文件时都需要npm run start以便更新变量。

回答by tarzen chugh

4 steps

4个步骤

1) npm install dotenv --save

1) npm install dotenv --save

2) Next add the following line to your app.

2)接下来将以下行添加到您的应用程序中。

require('dotenv').config()

require('dotenv').config()

3) Then create a .envfile at the root directory of your application and add the variables to it.

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

// contents of .env 

REACT_APP_API_KEY = 'my-secret-api-key'

4) Finally, add .envto your .gitignorefile so that Git ignores it and it never ends up on GitHub.

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

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

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

回答by Pablo

Today there is a simpler way to do that.

今天有一种更简单的方法可以做到这一点。

Just create the .env.local file in your root directory and set the variables there. In your case:

只需在根目录中创建 .env.local 文件并在那里设置变量。在你的情况下:

REACT_APP_API_KEY = 'my-secret-api-key'

Then you call it en your js file in that way:

然后你以这种方式在你的 js 文件中调用它:

process.env.REACT_APP_API_KEY

React supports environment variables since [email protected] .You don't need external package to do that.

React 支持环境变量,因为 [email protected] 。你不需要外部包来做到这一点。

https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables#adding-development-environment-variables-in-env

https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables#adding-development-environment-variables-in-env

*note: I propose .env.local instead of .env because create-react-app add this file to gitignore when create the project.

*注意:我建议使用 .env.local 而不是 .env 因为 create-react-app 在创建项目时将此文件添加到 gitignore。

Files priority:

文件优先级:

npm start: .env.development.local, .env.development, .env.local, .env

npm start: .env.development.local, .env.development, .env.local, .env

npm run build: .env.production.local, .env.production, .env.local, .env

npm run build: .env.production.local, .env.production, .env.local, .env

npm test: .env.test.local, .env.test, .env (note .env.local is missing)

npm 测试:.env.test.local、.env.test、.env(注意 .env.local 丢失)

More info: https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables

更多信息:https: //facebook.github.io/create-react-app/docs/adding-custom-environment-variables

回答by Aminu Kano

Webpack Users

Webpack 用户

If you are using webpack, you can install and use dotenv-webpackplugin, to do that follow steps below:

如果你使用 webpack,你可以安装和使用dotenv-webpack插件,按照以下步骤操作:

Install the package

安装包

yarn add dotenv-webpack

Create a .envfile

创建.env文件

// .env
API_KEY='my secret api key'

Add it to webpack.config.jsfile

将其添加到webpack.config.js文件

// webpack.config.js
const Dotenv = require('dotenv-webpack');

module.exports = {
  ...
  plugins: [
    new Dotenv()
  ]
  ...
};

Use it in your code as

在您的代码中使用它作为

process.env.API_KEY

For more information and configuration information, visit here

有关更多信息和配置信息,请访问此处

回答by Ankit Kumar Rajpoot

You have to install npm install env-cmd

你必须安装npm install env-cmd

Make .env in the root directory and update like this & REACT_APP_is the compulsory prefix for the variable name.

在根目录中创建 .env 并像这样更新 & REACT_APP_是变量名称的强​​制前缀。

REACT_APP_NODE_ENV="production"
REACT_APP_DB="http://localhost:5000"

Update package.json

更新 package.json

  "scripts": {
    "start": "env-cmd react-scripts start",
    "build": "env-cmd react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  }

回答by Carlos

1. Create the .envfile on your root folder

1.在根文件夹中创建.env文件

some sources prefere to use .env.developmentand .env.productionbut that's not obligatory.

有些来源更喜欢使用.env.development.env.production但这不是强制性的。

2. The name of your VARIABLE -must- begin with REACT_APP_YOURVARIABLENAME

2. 你的变量名 - 必须 - 以 REACT_APP_YOURVARIABLENAME 开头

it seems that if your environment variable does not start like that so you will have problems

看来,如果您的环境变量不是这样开始的,那么您就会遇到问题

3. Include your variable

3. 包括你的变量

to include your environment variable just put on your code process.env.REACT_APP_VARIABLE

包含您的环境变量只需放在您的代码中 process.env.REACT_APP_VARIABLE

You don't have to install any external dependency

您不必安装任何外部依赖项

回答by Fatema T. Zuhora

  1. Install dotenvas devDependencies:
  1. 安装dotenv为 devDependencies:
npm i --save-dev dotenv
  1. Create a .envfile in the root directory:
  1. .env在根目录创建一个文件:
my-react-app/
|- node-modules/
|- public/
|- src/
|- .env
|- .gitignore
|- package.json
|- package.lock.json.
|- README.md
  1. Update the .envfile like below & REACT_APP_is the compulsory prefix for the variable name.
  1. 更新如下.env文件 & REACT_APP_是变量名的强制前缀。
REACT_APP_BASE_URL=http://localhost:8000
REACT_APP_API_KEY=YOUR-API-KEY
  1. [ Optional but Good Practice] Now you can create a configuration file to store the variables and export the variable so can use it from others file.
  1. [可选但良好的实践] 现在您可以创建一个配置文件来存储变量并导出变量,以便可以从其他文件中使用它。

For example, I've create a file named base.jsand update it like below:

例如,我创建了一个名为base.js并更新它的文件,如下所示:

export const BASE_URL = process.env.REACT_APP_BASE_URL;
export const API_KEY = process.env.REACT_APP_API_KEY;
  1. Or you can simply just call the environment variable in your JS file in the following way:
  1. 或者,您可以通过以下方式简单地调用 JS 文件中的环境变量:
process.env.REACT_APP_BASE_URL