Skip to main content

添加自定义环境变量

注意:react-scripts@0.2.3 及更高版本提供此功能。

¥Note: this feature is available with react-scripts@0.2.3 and higher.

你的项目可以使用在你的环境中声明的变量,就好像它们是在你的 JS 文件中本地声明的一样。默认情况下,你将为你定义 NODE_ENV,以及以 REACT_APP_ 开头的任何其他环境变量。

¥Your project can consume variables declared in your environment as if they were declared locally in your JS files. By default you will have NODE_ENV defined for you, and any other environment variables starting with REACT_APP_.

警告:不要在你的 React 应用中存储任何秘密(例如私有 API 密钥)!

¥WARNING: Do not store any secrets (such as private API keys) in your React app!

环境变量嵌入到构建中,这意味着任何人都可以通过检查你的应用文件来查看它们。

¥Environment variables are embedded into the build, meaning anyone can view them by inspecting your app's files.

环境变量是在构建时嵌入的。由于 Create React App 生成静态 HTML/CSS/JS 包,它不可能在运行时读取它们。要在运行时读取它们,你需要将 HTML 加载到服务器的内存中并在运行时替换占位符,如 在这里描述。或者,你可以在更改它们时随时在服务器上重建应用。

¥The environment variables are embedded during the build time. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime. To read them at runtime, you would need to load HTML into memory on the server and replace placeholders in runtime, as described here. Alternatively you can rebuild the app on the server anytime you change them.

注意:你必须创建以 REACT_APP_ 开头的自定义环境变量。除了 NODE_ENV 之外的任何其他变量都将被忽略,以避免意外的 在可能具有相同名称的机器上公开私钥。更改任何环境变量都将要求你重新启动正在运行的开发服务器。

¥Note: You must create custom environment variables beginning with REACT_APP_. Any other variables except NODE_ENV will be ignored to avoid accidentally exposing a private key on the machine that could have the same name. Changing any environment variables will require you to restart the development server if it is running.

这些环境变量将在 process.env 上为你定义。例如,有一个名为 REACT_APP_NOT_SECRET_CODE 的环境变量将在你的 JS 中公开为 process.env.REACT_APP_NOT_SECRET_CODE

¥These environment variables will be defined for you on process.env. For example, having an environment variable named REACT_APP_NOT_SECRET_CODE will be exposed in your JS as process.env.REACT_APP_NOT_SECRET_CODE.

还有一个名为 NODE_ENV 的内置环境变量。你可以从 process.env.NODE_ENV 读取它。当你运行 npm start 时,它总是等于 'development',当你运行 npm test 时它总是等于 'test',而当你运行 npm run build 来制作生产包时,它总是等于 'production'。你不能手动覆盖 NODE_ENV。这可以防止开发者意外地将缓慢的开发版本部署到生产环境中。

¥There is also a built-in environment variable called NODE_ENV. You can read it from process.env.NODE_ENV. When you run npm start, it is always equal to 'development', when you run npm test it is always equal to 'test', and when you run npm run build to make a production bundle, it is always equal to 'production'. You cannot override NODE_ENV manually. This prevents developers from accidentally deploying a slow development build to production.

这些环境变量可用于根据项目的部署位置或使用版本控制之外的敏感数据有条件地显示信息。

¥These environment variables can be useful for displaying information conditionally based on where the project is deployed or consuming sensitive data that lives outside of version control.

首先,你需要定义环境变量。例如,假设你想在 <form> 中使用一个环境变量:

¥First, you need to have environment variables defined. For example, let’s say you wanted to consume an environment variable inside a <form>:

render() {
return (
<div>
<small>You are running this application in <b>{process.env.NODE_ENV}</b> mode.</small>
<form>
<input type="hidden" defaultValue={process.env.REACT_APP_NOT_SECRET_CODE} />
</form>
</div>
);
}

在构建期间,process.env.REACT_APP_NOT_SECRET_CODE 将替换为 REACT_APP_NOT_SECRET_CODE 环境变量的当前值。请记住,系统会自动为你设置 NODE_ENV 变量。

¥During the build, process.env.REACT_APP_NOT_SECRET_CODE will be replaced with the current value of the REACT_APP_NOT_SECRET_CODE environment variable. Remember that the NODE_ENV variable will be set for you automatically.

当你在浏览器中加载应用并检查 <input> 时,你会看到它的值设置为 abcdef,粗体文本将显示使用 npm start 时提供的环境:

¥When you load the app in the browser and inspect the <input>, you will see its value set to abcdef, and the bold text will show the environment provided when using npm start:

<div>
<small>You are running this application in <b>development</b> mode.</small>
<form>
<input type="hidden" value="abcdef" />
</form>
</div>

上面的表格正在从环境中寻找一个名为 REACT_APP_NOT_SECRET_CODE 的变量。为了使用这个值,我们需要在环境中定义它。这可以通过两种方式完成:在你的 shell 中或在 .env 文件中。在接下来的几节中将介绍这两种方式。

¥The above form is looking for a variable called REACT_APP_NOT_SECRET_CODE from the environment. In order to consume this value, we need to have it defined in the environment. This can be done using two ways: either in your shell or in a .env file. Both of these ways are described in the next few sections.

访问 NODE_ENV 对于有条件地执行操作也很有用:

¥Having access to the NODE_ENV is also useful for performing actions conditionally:

if (process.env.NODE_ENV !== 'production') {
analytics.disable();
}

当你使用 npm run build 编译应用时,压缩步骤会去除这种情况,并且生成的包会更小。

¥When you compile the app with npm run build, the minification step will strip out this condition, and the resulting bundle will be smaller.

在 HTML 中引用环境变量

¥Referencing Environment Variables in the HTML

注意:react-scripts@0.9.0 及更高版本提供此功能。

¥Note: this feature is available with react-scripts@0.9.0 and higher.

你还可以访问 public/index.html 中以 REACT_APP_ 开头的环境变量。例如:

¥You can also access the environment variables starting with REACT_APP_ in the public/index.html. For example:

<title>%REACT_APP_WEBSITE_NAME%</title>

请注意,上一节中的注意事项适用:

¥Note that the caveats from the above section apply:

  • 除了一些内置变量(NODE_ENVPUBLIC_URL)外,变量名必须以 REACT_APP_ 开头才能起作用。

    ¥Apart from a few built-in variables (NODE_ENV and PUBLIC_URL), variable names must start with REACT_APP_ to work.

  • 环境变量在构建时注入。如果你需要在运行时注入它们,改用这种方法

    ¥The environment variables are injected at build time. If you need to inject them at runtime, follow this approach instead.

在 Shell 中添加临时环境变量

¥Adding Temporary Environment Variables In Your Shell

定义环境变量可能因操作系统而异。同样重要的是要知道这种方式在 shell 会话的生命周期内是暂时的。

¥Defining environment variables can vary between OSes. It’s also important to know that this manner is temporary for the life of the shell session.

Windows (cmd.exe)

set "REACT_APP_NOT_SECRET_CODE=abcdef" && npm start

(注意:需要在变量赋值周围加上引号以避免尾随空格。)

¥(Note: Quotes around the variable assignment are required to avoid a trailing whitespace.)

Windows (Powershell)

($env:REACT_APP_NOT_SECRET_CODE = "abcdef") -and (npm start)

Linux、macOS(Bash)

REACT_APP_NOT_SECRET_CODE=abcdef npm start

.env 添加开发环境变量

¥Adding Development Environment Variables In .env

注意:react-scripts@0.5.0 及更高版本提供此功能。

¥Note: this feature is available with react-scripts@0.5.0 and higher.

要定义永久环境变量,请在项目的根目录中创建一个名为 .env 的文件:

¥To define permanent environment variables, create a file called .env in the root of your project:

REACT_APP_NOT_SECRET_CODE=abcdef

注意:你必须创建以 REACT_APP_ 开头的自定义环境变量。除了 NODE_ENV 之外的任何其他变量都将被忽略以避免 不小心暴露了机器上可能具有相同名称的私钥。更改任何环境变量都将要求你重新启动正在运行的开发服务器。

¥Note: You must create custom environment variables beginning with REACT_APP_. Any other variables except NODE_ENV will be ignored to avoid accidentally exposing a private key on the machine that could have the same name. Changing any environment variables will require you to restart the development server if it is running.

注意:更改 .env 文件后需要重启开发服务器。

¥Note: You need to restart the development server after changing .env files.

.env 文件应签入源代码管理(不包括 .env*.local)。

¥.env files should be checked into source control (with the exclusion of .env*.local).

还有哪些 .env 文件可以使用?

¥What other .env files can be used?

注意:react-scripts@1.0.0 及更高版本提供此功能。

¥Note: this feature is available with react-scripts@1.0.0 and higher.

  • .env:默认。

    ¥.env: Default.

  • .env.local:本地覆盖。为除测试之外的所有环境加载此文件。

    ¥.env.local: Local overrides. This file is loaded for all environments except test.

  • .env.development.env.test.env.production:特定于环境的设置。

    ¥.env.development, .env.test, .env.production: Environment-specific settings.

  • .env.development.local.env.test.local.env.production.local:本地覆盖特定于环境的设置。

    ¥.env.development.local, .env.test.local, .env.production.local: Local overrides of environment-specific settings.

左边的文件比右边的文件有更高的优先级:

¥Files on the left have more priority than files on the right:

  • npm start.env.development.local, .env.local, .env.development, .env

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

  • npm test.env.test.local.env.test.env(注意 .env.local 缺失)

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

如果机器没有明确设置这些变量,它们将作为默认值。

¥These variables will act as the defaults if the machine does not explicitly set them.

详情请参阅 dotenv 文档

¥Please refer to the dotenv documentation for more details.

注意:如果你正在为开发定义环境变量,你的 CI 和/或托管平台很可能也需要定义这些变量。请参阅他们的文档如何执行此操作。例如,请参阅 Travis CIHeroku 的文档。

¥Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need these defined as well. Consult their documentation how to do this. For example, see the documentation for Travis CI or Heroku.

.env 中扩展环境变量

¥Expanding Environment Variables In .env

注意:react-scripts@1.1.0 及更高版本提供此功能。

¥Note: this feature is available with react-scripts@1.1.0 and higher.

扩展机器上已有的变量以用于 .env 文件(使用 dotenv-expand)。

¥Expand variables already on your machine for use in your .env file (using dotenv-expand).

例如获取环境变量 npm_package_version

¥For example, to get the environment variable npm_package_version:

REACT_APP_VERSION=$npm_package_version
# also works:
# REACT_APP_VERSION=${npm_package_version}

或者扩展当前 .env 文件的局部变量:

¥Or expand variables local to the current .env file:

DOMAIN=www.example.com
REACT_APP_FOO=$DOMAIN/foo
REACT_APP_BAR=$DOMAIN/bar