后台-如何使用环境变量



Backstage文档指出,所有环境变量都必须是"暴露的";通过中央配置文件CCD_。

然而,官方文档并不清楚这些变量的使用,例如,在.ts.tsx文件中。

有人能帮忙吗,或者用代码举例说明这种使用是如何实现的?

对于前端和后端插件或代码都有一个标准配置API。API参考可以在这里找到。

你可以试试这样的东西:

import { Config } from '@backstage/config';
interface IBackendConfig {
KEY_1: string;
KEY_2: string;
KEY_3: string;
}
const getBackendConfig = (config: Config): IBackendConfig => {
return config.get<IBackendConfig>('backend.env');
}

在您的app-config.yaml

backend:
env:
KEY_1: "value1"
KEY_2: "value2"
KEY_3: "value3"

注意:由于此语法,配置键不能包含点。

访问env值的另一个选项是创建配置的子视图

config.getConfig('backend').getString('env'). 

也有同样的问题,最终只是在typescript文件中使用process.env.ENV_VAR,并在启动Backstage之前导出环境变量。

现在我可以帮助那些面临与我相同困难的人。

例如,如果您正在开发一个新的前端插件,则需要创建一个configSchema.d.ts文件,在该文件中指示它需要访问的设置/变量:

export interface Config {
exampleConfig: {
/**
* Base URL Example Service
* @visibility frontend
*/
baseUrl?: string;
/**
* Params at url in Example Service
* @visibility frontend
*/
getParamsUrl?: string;
/**
* Number of results that must be obtained
* @visibility frontend
*/
resultLimit?: number;
/**
* URL for PUT method
* @visibility frontend
*/
putUrl?: string;
/**
* Params for PUT method
* @visibility frontend
*/
putParamsUrl?: string;
/**
* Token Example Service
* @visibility frontend
*/
token?: string;
};

例如,在负责创建API的文件中,从@backstage/core-plugin-api包导入ConfigApi

以下是如何访问变量/配置的示例:

import { ConfigApi } from "@backstage/core-plugin-api";
[...]
export class ExampleClient implements ExampleApi {
private readonly backendBaseUrl: string;
private readonly baseUrl: string;
private readonly getParamsUrl: string;
private readonly queryResult: number;
private readonly putUrl: string;
private readonly putParamsUrl: string;
private readonly token: string;
private readonly managementAPi: ManagementRDMClient
constructor(options: { configApi: ConfigApi; fetchApi: FetchApi }
) {
this.backendBaseUrl = options.configApi.getString('backend.baseUrl');
this.baseUrl = options.configApi.getString('exampleConfig.baseUrl');
this.getParamsUrl = options.configApi.getString('exampleConfig.getParamsUrl');
this.queryResult = options.configApi.getNumber('exampleConfig.resultLimit');
this.putUrl = options.configApi.getString('exampleConfig.putUrl');
this.putParamsUrl = options.configApi.getString('exampleConfig.putParamsUrl');
this.token = options.configApi.getString('exampleConfig.token');
}
[...]
}

最新更新