ar099968
ar099968

Reputation: 7537

Import modules and export at runtime

Hi i have two config file, eg.:

config-one.ts

export const FOO = '1';
export const BAR = 1;

config-two.ts

export const FOO = '2';
export const BAR = 2;

both files are imported in config.ts.

config.ts

import * as configOne from './config-one.ts';
import * as configTwo from './config-two.ts';

I want at some contition export config-one or config-two like as exported by config.ts

if ( some condition ){
    export configOne;
} else {
    export configTwo;
}

usage in other file

foo.ts

import { FOO, BAR } from './config.ts';

Is possible in typescript?

Upvotes: 1

Views: 652

Answers (1)

Ali Habibzadeh
Ali Habibzadeh

Reputation: 11548

Dynamic import is enough to make dynamic export happen:

config-one.ts

export const config1 = "config1";

config-two.ts

export const config2 = "config2";

index.ts

const whatever = true;

const getConfig = () => {
  if (whatever) {
    return import("./config-one");
  }
  return import("./config-two");
};

tsconfig

...
"moduleResolution": "Node",
"module": "CommonJS",
...

usage example:

async function main() {
  console.log(await getConfig());
}

main().catch(console.log);

Upvotes: 1

Related Questions