我试图隐藏我的API密钥,当我提交到GitHub,我已经通过论坛的指导,特别是下面的帖子:

我如何隐藏一个API密钥在创建反应应用程序?

我做了修改并重新启动Yarn。我不确定我做错了什么-我添加了一个。env文件到我的项目的根(我命名为process.env),在文件中我只是把REACT_APP_API_KEY = 'my-secret-api-key'。

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

performSearch = (query = 'germany') => { 查询https://api.unsplash.com/search/photos?query=获取(“$ {}client_id = $ {REACT_APP_API_KEY}’) .then(response => response.json()) .then(responseData => { this.setState ({ 结果:responseData.results, 加载:假 }); }) .catch(error => { console.log('读取和解析数据出错',Error); }); }


当前回答

你必须安装npm install env-cmd

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

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

更新package.json

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

其他回答

在CREATE REACT APP中使用环境变量的步骤(不含dotenv包)

Create a new file called .env in the root folder of the project (NOT inside src folder but one level up. Remember, it should be at the same level as package.json (THIS IS VERY IMPORTANT!!) Define your variables like so (Note that every variable you define should start with REACT_APP_) Example : .env file REACT_APP_ACCESS_KEY=8Sh9ZLwZevicWC-f_lmHvvyMu44cg3yZBU Note: You don't have to enclose the value in "" or '' Now you can use the variable in any of your components like so const apiKey = process.env.REACT_APP_ACCESS_KEY The name should match the key given in the .env file Now before you try this out, always remember to restart the local server. Once you run npm start it works. This step applies whenever you make changes to the .env file. We generally forget this step so it might not work. Optionally, check if .env entry is present in .gitignore file. If the entry of .env exists in .gitignore then your .env file will not be pushed to github(This is the reason why we use .env in the first place).

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

步骤1 ReactDocs

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

1.1创建Root/.env

#.env file
REACT_APP_SECRET_NAME=secretvaluehere123

重要提示:它必须以REACT_APP_开头。

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构建环境问题

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

设置好环境变量后,必须再次运行npm start。这就是我所缺少的部分。在自动重新加载时,.env变量不会更新。

Webpack用户

如果你正在使用Webpack,你可以安装和使用dotenv-webpack插件。要做到这一点,请遵循以下步骤:

安装包

yarn add dotenv-webpack

创建一个.env文件

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

将它添加到webpack.config.js文件中:

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

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

在代码中使用它

process.env.API_KEY

有关更多信息和配置信息,请访问dotenv-webpack。

Install dotenv as devDependencies: npm i --save-dev dotenv Create a .env file in the root directory: my-react-app/ |- node-modules/ |- public/ |- src/ |- .env |- .gitignore |- package.json |- package.lock.json. |- README.md Update the .env file like below & REACT_APP_ is the compulsory prefix for the variable name. REACT_APP_BASE_URL=http://localhost:8000 REACT_APP_API_KEY=YOUR-API-KEY [ 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. For example, I've create a file named base.js and update it like below: export const BASE_URL = process.env.REACT_APP_BASE_URL; export const API_KEY = process.env.REACT_APP_API_KEY; Or you can simply just call the environment variable in your JS file in the following way: process.env.REACT_APP_BASE_URL