部署后未定义的 React 应用程序环境变量
React Application Environment Variable Undefined after Deploying
应用程序是通过 Gitlab Kubernetes 部署的。部署后,环境未定义
只是想知道我如何在 React 中使用 env,就像 Next.js
你可以使用 React-dotenv : https://www.npmjs.com/package/react-dotenv
示例代码:
import React from "react";
import env from "react-dotenv";
export function MyComponent() {
return <div>{env.MY_VARIBLE}</div>;
}
deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: test
spec:
replicas: 1
selector:
matchLabels:
component: test
template:
metadata:
labels:
component: test
spec:
imagePullSecrets:
- name: test-image
containers:
- name: test
image:test/image:v12
ports:
- containerPort: 80
env:
- name: MY_VARIBLE
value: "hello world"
选项 2
使用config.json存储环境变量
config.json
{
DATA: "$DATA",
URL: "$URL"
}
代码示例
import { Component } from '@angular/core';
import Config from "../config.json";
@Component({
selector: 'app-root',
templateUrl: './app.hello.html'
})
export class AppComponent {
environment = Config.DATA;
baseUrl = Config.URL;
}
应用程序是通过 Gitlab Kubernetes 部署的。部署后,环境未定义
只是想知道我如何在 React 中使用 env,就像 Next.js
你可以使用 React-dotenv : https://www.npmjs.com/package/react-dotenv
示例代码:
import React from "react";
import env from "react-dotenv";
export function MyComponent() {
return <div>{env.MY_VARIBLE}</div>;
}
deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: test
spec:
replicas: 1
selector:
matchLabels:
component: test
template:
metadata:
labels:
component: test
spec:
imagePullSecrets:
- name: test-image
containers:
- name: test
image:test/image:v12
ports:
- containerPort: 80
env:
- name: MY_VARIBLE
value: "hello world"
选项 2
使用config.json存储环境变量
config.json
{
DATA: "$DATA",
URL: "$URL"
}
代码示例
import { Component } from '@angular/core';
import Config from "../config.json";
@Component({
selector: 'app-root',
templateUrl: './app.hello.html'
})
export class AppComponent {
environment = Config.DATA;
baseUrl = Config.URL;
}