ANIK ISLAM SHOJIB
ANIK ISLAM SHOJIB

Reputation: 3258

dynamic import typescript express

import * as dotenv from 'dotenv';
dotenv.config();
const env: string = process.env.NODE_ENV || 'development';

export const cnf = async () => {
  const data = await import('./config.' + env);
  console.log('data');
  return data;
};

from my app.ts

import * as confgg from '../../config';
class App {
  public app: express.Application;
  private host: string = process.env.IP || process.env.ADMIN_HOST || cnf.get('web.host');
  private port: number = parseInt(process.env.PORT, 10) || parseInt(process.env.ADMIN_PORT, 10) || cnf.get('web.port');

  private mysql = MySql.getInstance();

  constructor(private readonly config: AppConfig) {
    this.app = express();
    this.initializeInfoLoggingHandling();
    console.log(confgg)
  }

this console.log printing

{ cnf: [Function (anonymous)] }

but it's supposed to print some array. I am just trying to load my configuration dynamically.

Upvotes: 0

Views: 524

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074949

this console.log printing { cnf: [Function (anonymous)] }

but it's supposed to print some array.

It's supposed to be showing exactly that, because you're exporting a function using a named export, but importing the module namespace object, which has a property for each export. So you're seeing an object (the module namespace object) with a property (cnf) which refers to a function (the async function you're exporting).

If you want to use dynamic import and make your export the result of that dynamic import, you need to make your module wait for it with top-level await:

config.ts:

import * as dotenv from 'dotenv';
dotenv.config();
const env: string = process.env.NODE_ENV || 'development';

// Top-level await waits for the import to finish
const data = await import('./config.' + env);
console.log('data');

export default data; // See note below

then import the default rather than the module namespace object:

import confgg from '../../config';

You haven't shown what the contents of your config.development etc. files are, but data will be a module namespace object for the configuration information, you may want to export one of its properties instead.


Note that top-level await is still just a proposal, though it's very far along and present in popular JavaScript engines and module bundlers.

Upvotes: 1

Related Questions