Node + TypeScript: Export Default Something based on Conditions

Updated: February 4, 2022 By: Pennywise Post a comment

There might be times when you might want to export something based on one or multiple conditions (for example, you want to export configuration information like database, API keys, etc for development environment and production environment). Unfortunately, you cannot put your export statement inside an if/else or switch/case check. To archive the goal, you can do like the example below:

let config;
if (process.env.NODE_ENV === 'development') {
  config = {
    host: 'localhost',
    database: 'test',
    username: 'test',
    password: '123456'
  }
} else {
  config = {
    /* ... */
  }
}

export default config;

The scripts section in package.json:

"scripts": {
    "start": "NODE_ENV=development node ./build/index.js",
    "dev": "NODE_ENV=development nodemon ./src/index.ts",
    "build": "tsc"
},

Further reading:

You can also check out our Node.js category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles