【问题标题】:React Application Environment Variable Undefined after Deploying部署后反应应用程序环境变量未定义
【发布时间】:2021-09-13 12:33:26
【问题描述】:

应用程序是通过 Gitlab Kubernetes 部署的。部署后,环境未定义

只是想知道如何在 React 中使用 env,例如 Next.js

【问题讨论】:

    标签: reactjs environment-variables


    【解决方案1】:

    你可以使用 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;
    }
    

    阅读更多:https://developers.redhat.com/blog/2021/03/04/making-environment-variables-accessible-in-front-end-containers#inject_the_environment_variables

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-24
      • 2019-08-13
      • 2019-05-30
      • 1970-01-01
      • 2023-02-02
      • 2018-05-21
      • 1970-01-01
      • 2021-12-12
      相关资源
      最近更新 更多