如何在运行时读取 config.ts 文件?

huangapple go评论64阅读模式
英文:

How to read a config.ts file at runtime?

问题

我有一个如下的config.ts文件:

import someConfig from './someConfigModel';

const config = {
  token: process.env.API_TOKEN,
  projectId: 'sample',
  buildId: process.env.BUILD_ID,
};

export default config as someConfig;

有没有一种在运行时通过传递该文件的名称来读取此配置的方法?同时,我希望能够自动填充类似token的配置属性。

英文:

I have a config.ts file as below:

import someConfig from './someConfigModel';

const config = {
  token: process.env.API_TOKEN,
  projectId: 'sample',
  buildId: process.env.BUILD_ID,
};

export default config as someConfig;

Is there a way at runtime to read this config in another module by passing the name of this file? Also I would like to see the config properties like token be auto-filled.

答案1

得分: 0

已更新的配置文件:

// config.ts
import SomeConfig from './someConfigModel';

export const config: SomeConfig = {
  token: process.env.API_TOKEN,
  projectId: 'sample',
  buildId: process.env.BUILD_ID,
};

解决方案:

const module = await import('./config.ts');
const _config = module['config'] as SomeConfig;
英文:

Updated config file:

// config.ts
import SomeConfig from './someConfigModel';

export const config: SomeConfig = {
  token: process.env.API_TOKEN,
  projectId: 'sample',
  buildId: process.env.BUILD_ID,
};

Solution:

const module = await import('./config.ts');
const _config = module['config'] as someConfig;

huangapple
  • 本文由 发表于 2023年4月17日 21:42:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76035814.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定