简体   繁体   English

是否可以在 React 项目中使用 dotenv?

[英]Is it possible to use dotenv in a react project?

I am trying to set some environment variables (for making API calls to dev/prod endpoints, keys depending on dev/prod, etc.) and I'm wondering if using dotenv will work.我正在尝试设置一些环境变量(用于对 dev/prod 端点进行 API 调用,密钥取决于 dev/prod 等),我想知道使用 dotenv 是否可行。

I've installed dotenv, and I am using webpack.我已经安装了 dotenv,我正在使用 webpack。

My webpack entry is main.js , so in this file I've put require('dotenv').config()我的 webpack 条目是main.js ,所以在这个文件中我把require('dotenv').config()

Then, in my webpack config, I've put this:然后,在我的 webpack 配置中,我把这个:

  new webpack.EnvironmentPlugin([
    'NODE_ENV',
    '__DEV_BASE_URL__'  //base url for dev api endpoints
  ])

However, it is still undefined.然而,它仍然是未定义的。 How can I do this correctly?我怎样才能正确地做到这一点?

Sorry for picking up old question, but很抱歉提出旧问题,但是
react-scripts actually uses dotenv library under the hood. react-scripts实际上在底层使用了dotenv库。

With react-scripts@0.2.3 and higher, you can work with environment variables this way:使用 react-scripts@0.2.3 及更高版本,您可以通过以下方式使用环境变量:

  1. create .env file in the root of the project在项目根目录创建.env文件
  2. set environment variables starting with REACT_APP_ there在那里设置以REACT_APP_开头的环境变量
  3. access it by process.env.REACT_APP_... in components通过process.env.REACT_APP_...在组件中访问它

.env .env

REACT_APP_BASE_URL=http://localhost:3000

App.js应用程序.js

const BASE_URL = process.env.REACT_APP_BASE_URL;

See docs for more details.有关更多详细信息,请参阅文档

The short answer is no.最简洁的答案是不。 A browser cannot access local or server environment variables so dotenv has nothing to look for.浏览器无法访问本地或服务器环境变量,因此 dotenv 无需查找。 Instead, you specify ordinary variables in your React application, usually in a settings module.相反,您在 React 应用程序中指定普通变量,通常在设置模块中。

Webpack can be made to take environment variables from the build machine and bake them into your settings files.可以让 Webpack 从构建机器中获取环境变量并将它们烘焙到您的设置文件中。 However, it works be actually replacing strings at build-time, not run-time.但是,它实际上是在构建时而不是运行时替换字符串。 So each build of your application will have the values hard-coded into it.因此,您的应用程序的每个构建都会将值硬编码到其中。 These values would then be accessible through the process.env object.然后可以通过process.env对象访问这些值。

var nodeEnv = process.env.NODE_ENV;

Additionally, you could use the DefinePlugin for webpack which lets you explicitly specify different values depending on your build target (dev, prod, etc.).此外,您可以使用DefinePlugin的 DefinePlugin,它允许您根据构建目标(dev、prod 等)明确指定不同的值。 Note that you have to JSON.stringify all values passed into it.请注意,您必须JSON.stringify传递给它的所有值。

new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
}),

This is fine for any sort of public details but should never be used for any sort of private keys, passwords or API secrets .这适用于任何类型的公共细节,但绝不能用于任何类型的私钥、密码或 API 机密 This is because any values baked in are publicly accessible and could be used maliciously if they contain sensitive details.这是因为任何烘焙的值都是可公开访问的,如果它们包含敏感细节,则可能被恶意使用。 For those sorts of things, you need to write some server-side code and build a simple API which can authenticate with the 3rd party API using the secrets, then pass the relevant details along to your client-side application.对于这些类型的事情,您需要编写一些服务器端代码并​​构建一个简单的 API,该 API 可以使用机密与 3rd 方 API 进行身份验证,然后将相关详细信息传递给您的客户端应用程序。 Your server-side API acts as an intermediary, protecting your secrets while still getting the data you need.您的服务器端 API 充当中介,保护您的秘密,同时仍能获取您需要的数据。

Actually, you can use dotenv in your React app with webpack.实际上,您可以在带有 webpack 的 React 应用程序中使用 dotenv。 Moreover, there are several ways of doing it.此外,有几种方法可以做到这一点。 However, keep in mind that it's still a build-time configuration.但是,请记住,它仍然是构建时配置。

  1. A similar way to the answer above.与上面的答案类似的方法。 You import dotenv in your webpack config and use DefinePlugin to pass the variables to your React app.您在 webpack 配置中导入dotenv并使用 DefinePlugin 将变量传递给您的 React 应用程序。 More complete guide on how you can inject your .env files depending on current configuration could be found in this blog .可以在此博客中找到有关如何根据当前配置注入.env文件的更完整指南。

  2. Using a dotenv-webpack plugin .使用dotenv-webpack插件 I personally find it really convenient.个人觉得真的很方便。 Let's say you have environments: dev , staging and prod .假设您有环境: devstagingprod You create .env file for each environment ( .env.dev , .env.staging , etc).您为每个环境( .env.dev.env.staging等)创建 .env 文件。 In your webpack configuration you need to pick a correct file for the environment:在你的 webpack 配置中,你需要为环境选择一个正确的文件:

     const Dotenv = require('dotenv-webpack'); module.exports = (env, argv) => { const envPath = env.ENVIRONMENT ? `.env.${env.ENVIRONMENT}` : '.env'; const config = { ... plugins: [ new Dotenv({ path: envPath }) ] }; return config; };

When you build the app for a particular environment, just pass the environment name to webpack:当您为特定环境构建应用程序时,只需将环境名称传递给 webpack:

webpack --config webpack.config.js --env.ENVIRONMENT=dev
  1. Create .env file创建 .env 文件
    API_URL=http://localhost:8000
  2. Install dotenv npm package安装 dotenv npm 包
    $ npm install --save-dev dotenv
  3. Config webpack to add env variables配置 webpack 添加环境变量
    const webpack = require('webpack'); const dotenv = require('dotenv'); module.exports = () => { // call dotenv and it will return an Object with a parsed key const env = dotenv.config().parsed; // reduce it to a nice object, the same as before const envKeys = Object.keys(env).reduce((prev, next) => { prev[`process.env.${next}`] = JSON.stringify(env[next]); return prev; }, {}); return { plugins: [ new webpack.DefinePlugin(envKeys) ] };
  4. Great job!做得好! Enjoy React and dotenv.享受 React 和 dotenv。

I Just created a config.json in the source folder:我刚刚在源文件夹中创建了一个 config.json:

{
    "api_url" : "http://localhost:8080/"
}

then required it in the file I needed it然后在我需要它的文件中要求它

const config = require('./config.json');

and used config.api_url并使用了 config.api_url

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM