简体   繁体   English

Nx React 在运行时注入环境变量

[英]Nx React inject environment variables at runtime

I have a Nx monorepo with multiple react applications.我有一个带有多个反应应用程序的 Nx monorepo。

I want to be able to run the build once and then deploy the same build to multiple environments (eg dev, test, production).我希望能够运行一次构建,然后将相同的构建部署到多个环境(例如开发、测试、生产)。

What I used to do in previous projects where I wasn't using Nx, it was to have a env.js file in the /public folder and a script tag in the head of index.html to get the env.js file.我以前在不使用 Nx 的项目中所做的,是在/public文件夹中有一个env.js文件,在index.html的头部有一个脚本标签来获取env.js文件。

is it possible to achieve the same result with Nx?是否可以使用 Nx 达到相同的结果?

NX by default gives you an /environments/environment.ts file where you can store your environment variables. NX默认为您提供一个/environments/environment.ts文件,您可以在其中存储环境变量。

You can import it into your app with:您可以使用以下命令将其导入您的应用程序:

import { environment } from './environments/environment'

You can swap out environments during the build process with the workspace.json file.您可以在构建过程中使用workspace.json文件交换环境。

...
"configurations": {
  "production": {
    "fileReplacements": [
      {
        "replace": "apps/client/src/environments/environment.ts",
        "with": "apps/client/src/environments/environment.prod.ts"
      }
    ],
  ...

If you want to inject environment variables into your index.html file, you have to actually set those when you're building your app.如果要将环境变量注入index.html文件,则必须在构建应用程序时实际设置这些变量。 For local builds,对于本地构建,

Locally本地

I created an .env file at the root of the react project and put the variables there我在 react 项目的根目录创建了一个.env文件并将变量放在那里

Hosted Environments托管环境

We added the envvars to our CI during the build process.我们在构建过程中将 envvars 添加到我们的 CI 中。

- name: Build Applications
  run: |
    NX_DOMAIN_NAME="My Super Domain" npx nx run-many --target=build --configuration=production

https://nx.dev/latest/react/guides/environment-variables#using-environment-variables-in-indexhtml https://nx.dev/latest/react/guides/environment-variables#using-environment-variables-in-indexhtml

Set variable prefixed with NX_ into your .env file:将前缀为 NX_ 的变量设置到 .env 文件中:

NX_SERVER_URL=http://localhost:8080

Then it will be accessable within your react app:然后它将可以在您的反应应用程序中访问:

const url = process.env.NX_SERVER_URL

Or in html document:或者在 html 文档中:

<p>The server url is %NX_SERVER_URL%.</p>

Also NX docs还有NX 文档

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

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