Utilizing TypeScript with Express for dynamic imports

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

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

from my app.ts

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

  private mysql = MySql.getInstance();

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

this console.log printing

{ customConfig: [Function (anonymous)] }

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

Answer №1

the console.log is displaying { cnf: [Function (anonymous)] }

instead of the expected array.

This happens because you are exporting a function using a named export, but importing the module namespace object which contains properties for each export. Therefore, what you're seeing is an object (the module namespace object) with a property (cnf) that points to a function (the async function being exported).

If you intend to use dynamic import and have your export result from that, you need to ensure your module waits for it using 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 instead of the module namespace object:

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

You haven't provided details about the contents of your config.development files, but data will be a module namespace object containing configuration information - consider exporting one of its properties instead.


It's worth noting that top-level await is currently a proposed feature, although it is already supported by popular JavaScript engines and module bundlers.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

To utilize the Heroku Express + Postgres addon, one must have elevated permissions

[2022-11-01 14:45:37.218] [ERROR] application - Connection postgres://user123:password456@database.example.com:5432/db_name123 requires elevated permissions I'm currently working on deploying an application using Node.js + Express + Sequelize + ...

Parsing JSON in an Express application

I have developed a small application to test a larger one that I am currently working on. The small application reads data from a CSV file and then attempts to send this data to my API endpoint using POST requests. This is necessary as I need to send a lar ...

TypeError: Unable to find TextEncoder in mongoose and jest when using TypeScript

Currently, I am working on a project using Node 14 along with Express v4.16.3 and Typescript (v4.7.4). Recently, I added Mongoose (v6.5.2) to the project, and while the logic code seems fine, most of the tests executed by Jest (v26.4.2) are failing with th ...

Implementing virtual hosts and HTTPS encryption

Is it possible to configure vhosts on Express with https? This is my current code without SSL: var express = require('express'); var vhost = require('vhost'); var path = require('path'); var appOne = express(); var appTwo = ...

Creating a constructor that assigns values by using interfaces that are built upon the class

Looking at this interface/class example export interface MyErrorI { something: boolean; } export class MyError extends Error implements MyErrorI { public something = false; constructor(message: string, key: keyof MyErrorI ) { super(m ...

TypeScript: Unable to fetch the property type from a different type

Currently, I'm using create-react-app with its TypeScript template. However, I encountered an issue while attempting to retrieve the type of the property 'pending' in 'GenericAsyncThunk', similar to how it's done in the redux- ...

Node.js and Express: Delivering Seamless Video Streaming via HTTP 206 Partial Content

Having a binary file like an mp4 video in a MarkLogic database, I am utilizing the Node.js API of the database to stream this document in segments. The structure is as follows: html document <video controls="controls" width="600"> <source src= ...

Setting up a web server with a cyclical challenge

I've encountered an issue while hosting my server.js file with the configured API on Cyclic. The deployment was successful, but every endpoint call is returning a status 500 error. Additionally, I have hosted the React front-end on github pages. I&apo ...

The data type 'AbstractControl | null' cannot be assigned to type 'FormGroup'

I am facing an issue with passing the [formGroup] to child components in Angular. The error message says Type 'AbstractControl | null' is not assignable to type 'FormGroup'. I have double-checked my conditions and initialization, but I ...

Encountering [object, Object] while attempting to display JSON object retrieved from req.body in the console

While attempting to insert a product's details into my API's PostgreSQL database using Postman, I encountered an issue where the values of the specs key were displayed as [object Object] instead of showing the complete data. As a result, even in ...

What is the best way to explain the concept of type indexing in TypeScript using its own keys?

I'm still learning TypeScript, so please bear with me if my question sounds basic. Is there a way to specify the index for this type so that it utilizes its own keys rather than just being an object? export type TypeAbCreationModal = { [index: stri ...

Sharing a JSON file with another address using Express.js

Currently embarking on my journey to learn Express. I am looking to send a JSON file to another location for processing after receiving it from a webhook request using a POST URL endpoint. The plan is to pass this JSON file to a CPP program. Below is the ...

Unpacking the information in React

My goal is to destructure coinsData so I can access the id globally and iterate through the data elsewhere. However, I am facing an issue with TypeScript on exporting CoinProvider: Type '({ children }: { children?: ReactNode; }) => void' is no ...

Extracting Unprocessed Data with Node.js Express

I am currently working with an Express server that handles a login form page: const app = express(); // part A app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.urlencoded()); app.get('/login', ...

typescript unconventional syntax for object types

As I was going through the TypeScript handbook, I stumbled upon this example: interface Shape { color: string; } interface Square extends Shape { sideLength: number; } var square = <Square>{}; square.color = "blue"; square.sideLength = 10; ...

The toggle-input component I implemented in React is not providing the desired level of accessibility

Having an accessibility issue with a toggle input while using VoiceOver on a Mac. The problem is that when I turn the toggle off, VoiceOver says it's on, and vice versa. How can I fix this so that VoiceOver accurately states whether the toggle is on o ...

Tips for sending <p> data to a router function with HTML

I am currently working on a page where users are presented with a list of unverified accounts, each containing its own form element. Each form has a "submit" button that triggers a POST call to /verify. However, I am facing an issue where the data within t ...

Error: The object is not defined (evaluating '_$$_REQUIRE(_dependencyMap[32], "react-native-safe-area-context").SafeAreaView')

I am currently working on developing a chat application using react-native with the following dependencies: "dependencies": { "@react-native-async-storage/async-storage": "~1.17.3", "@react-native-community/masked ...

I encountered an unexpected obstacle while reloading my Next.js application with animejs. The error message reads: "SyntaxError: Unexpected token 'export'." This unwelcome occurrence took place during the

Encountering an error with animejs when reloading my Next.js app: An unexpected token 'export' is causing a SyntaxError. This issue occurred during the page generation process. The error originates from file:///Users/.../node_modules/animejs/lib ...

What is the best way to access a component's data within its method using Vue and Typescript?

Starting a Vue.js project with TypeScript and using single file components instead of class-styled ones has been my goal. However, I have encountered a recurring issue where I get error TS2339 when trying to reference my components' data using the "th ...