You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Backstage技术问题:如何在代码中使用环境变量?

Backstage环境变量在.ts/.tsx文件中的使用方法

1. 先在app-config.yaml中暴露环境变量

按照要求在中心配置文件里定义配置项并绑定系统环境变量,示例:

# app-config.yaml
api:
  # 绑定系统环境变量BACKEND_API_URL,默认值为http://localhost:7007
  baseUrl: ${BACKEND_API_URL:http://localhost:7007}

app:
  # 前端可访问的配置,同样绑定环境变量
  frontendApiUrl: ${BACKEND_API_URL:http://localhost:7007}

2. 后端.ts文件中读取配置

后端通过Config服务注入来读取配置,示例如下:

服务类中使用

import { Config, injectable } from '@backstage/config';

@injectable()
export class MyBackendService {
  constructor(private readonly config: Config) {}

  fetchData() {
    const apiUrl = this.config.getString('api.baseUrl');
    // 使用apiUrl发起请求等操作
    return fetch(`${apiUrl}/data`);
  }
}

后端插件初始化时使用

import { createBackendPlugin } from '@backstage/backend-plugin-api';
import { coreServices } from '@backstage/backend-plugin-api';

export const myBackendPlugin = createBackendPlugin({
  pluginId: 'my-backend-plugin',
  register(env) {
    env.registerInit({
      deps: { config: coreServices.config },
      async init({ config }) {
        const apiUrl = config.getString('api.baseUrl');
        console.log('后端API地址:', apiUrl);
      },
    });
  },
});

3. 前端.ts/.tsx文件中读取配置

前端需通过configApiRef获取配置,确保配置在app等前端可访问节点下,示例:

React组件中使用

import { useApi } from '@backstage/core-plugin-api';
import { configApiRef } from '@backstage/core-plugin-api';

export const MyFrontendComponent = () => {
  const configApi = useApi(configApiRef);
  // 读取前端可访问的配置
  const apiUrl = configApi.getString('app.frontendApiUrl');

  return (
    <div className="p-4">
      <h3>当前API地址:{apiUrl}</h3>
    </div>
  );
};

前端插件注册时使用

import { createPlugin } from '@backstage/core-plugin-api';

export const myFrontendPlugin = createPlugin({
  id: 'my-frontend-plugin',
  register({ config }) {
    const apiUrl = config.getString('app.frontendApiUrl');
    console.log('前端API地址:', apiUrl);
  },
});

注意事项

  • 敏感配置(如密钥)不要放到app节点下,避免前端可访问
  • 可选配置使用getOptionalString方法,防止配置不存在时抛出错误:config.getOptionalString('api.optionalUrl')
  • 环境变量优先级:系统环境变量 > app-config.local.yaml > app-config.yaml

内容的提问来源于stack exchange,提问作者Paulo Eduardo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 17:55:19