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

Angular Universal SSR - prerendering static content

After updating to the latest Angular version 10, I encountered an issue when trying to run a static prerender. The error message displayed is: Unhandled Promise rejection: Cannot read property 'moduleType' of undefined. Despite trying various con ...

Data cannot be transferred to a child element unless it has been initialized during the definition phase

Passing an array data from parent to child component has brought up some interesting scenarios: parent.component.html: <child-component ... [options]="students" > </child-component> Status I: Setting the array on definition ...

I am having trouble getting my custom colors to work with hover effects in Tailwind CSS

The code I have written is for a header component in Next.js with Typescript and Tailwind. I named it Header_2 to represent a component display in a library. Initially, the custom colors were not rendering as expected, but I managed to resolve the issue by ...

What could be the reason for TypeScript throwing an error despite having a condition in place?

Having an issue with TypeScript (TS2531) and its non-null type checking. Here's the scenario: if (this.formGroup.get('inseeActivityCode') !== null) { mergedCompanyActivity.inseeActivityCode = this.formGroup.get('inseeActivityCode&ap ...

Next app unable to fetch cookie set by Express app

My project involves an app built on react/next and a server built on express. The process begins with a user authenticating via Github Oauth using passport.js, after which the server sends a connect.sid cookie. This cookie is crucial for rendering data to ...

"Troubleshooting: Why are errors not appearing in ts-node

Whenever I encounter an error in my code while compiling with ts-node, the error does not seem to appear in the console. For instance:let data = await fs.readFileSync(path); In the following code snippet, I am using "fs" to read a file by passing a path ...

Encountering difficulty when trying to define the onComplete function in Conf.ts. A type error is occurring, stating that '(passed: any) => void' is not compatible with type '() => void'.ts(2322)'

I have been developing a custom Protractor - browserstack framework from the ground up. While implementing the onComplete function as outlined on the official site in conf.ts - // Code snippet to update test status on BrowserStack based on test assertion ...

Tips for avoiding HTTPS issues when communicating between Apache and Node Express servers

Recently, I repurposed an old laptop to run Ubuntu Server 18.04 and gave it a fixed IP address of 192.168.0.36 on my local network for easy SSH access from my main machine. This laptop is hosting a website written in React using the Apache server (built w ...

Tips for pairing MongoDB queries across fields

Imagine having a set of data: { id: 0, likes: 1}, { id: 1, likes: 0}, // ^ indicating a match { id: 2, likes: 0}, { id: 3, likes: 0} *The 'likes' column refers to the matching 'id'. For example, id:0 matches with id:1 because id:0 lik ...

ag-grid's onGridReady function is not functioning properly

I am trying to dynamically load ag-grid when a button is clicked, but I have encountered issues with both of my approaches. Here is my code for the first method: onBtnClick(){ this.gridOptions ={ onGridReady : function(){ console ...

TS1055 occurs when utilizing async/await with a custom type alias

I defined a custom type alias: export type ActivationPromise = Promise<void>; I have created the following two functions: async function derp(): ActivationPromise { await test(); } function test(): ActivationPromise { return Promise.resol ...

Is there a way to customize the slicing of *ngFor in a component according to the components it is being injected into?

This code snippet represents a component that needs to be included in other components: <div class="row"> <div class="col-12 [...]" *ngFor="let course of courses"> <div class="card"> ...

What are the steps for inserting an API key into Swagger?

I've been exploring various techniques to implement basic API key authorization in Swagger (express swagger). Here's a snippet from my manifest that contains relevant information. { ... "main": "app.js", "dependencies": { "express": "^ ...

The ES6 reduce method is not giving the expected result

In Image 1, the output you will see if you log the final array from Snippet 1. My goal is to transform my array to match the format shown in Image 2. I attempted using lodash's _.uniqBy() method [Snippet 2], but the logged output of the reduce varia ...

What is the best way to integrate the Heroku-generated server port into my Vue.js front-end application?

One of the challenges I am facing is related to communication between the server and client, specifically in the context of deploying an express/mongoDB app on Heroku. The issue arises because Heroku assigns a new port every time the server starts, which i ...

Loading the value of a Subject variable in an Angular 2 application using Typescript

I am currently developing an Angular2 application where I am loading data from a service into my component as a subject. public type1Choisi: any; constructor( public formeService: FormeService, ...) { this.formeService._type1.subscribe(type1 => ...

Issue TS2339: The object does not have a property named 'includes'

There seems to be an issue that I am encountering: error TS2339: Property 'includes' does not exist on type '{}'. This error occurs when attempting to verify if a username is available or not. Interestingly, the functionality works ...

The router.patch method is throwing a 404 error with the message "resource not found"

I've encountered an issue with the patch method in my small Node API - my router.patch is returning a 404 error. Here's how my route looks: router.param('userId', findById); router.patch( '/api/projects/update/:projectId/:user ...

Curious about the missing dependencies in React Hook useEffect?

I'm encountering the following issue: Line 25:7: React Hook useEffect has missing dependencies: 'getSingleProductData', 'isProductOnSale', and 'productData'. Either include them or remove the dependency array react-hoo ...

Using Express and Node.js, fetch an image from one localhost and transfer it to another localhost

I am currently developing a NodeJs and Angular app The server is running on http://localhost:9000 While the app itself runs on http://localhost:4200 One of my endpoints looks like this http://localhost:9000/users, which I use to fetch all user data The ...