0
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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

FWIW, I go into JavaScript module import and export, dynamic import, and top-level await in Chapters 13 and 19 of my recent book, JavaScript: The New Toys. Links in my profile if you're interested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.