Home > Mobile >  Dynamic import based on environment variable
Dynamic import based on environment variable

Time:11-14

In a project I have a environment varible which should be used to specifiy wheter we would like to use HTTPS or not:

SSL_ENABLED=1

Based on this environment variables I am now trying to use the https or http module:

import * as http from parseInt(process.env.SSL_ENABLED || '', 10) ? 'https' : 'http'

const server = http.createServer(...)

The import above throws the following typescript error:

TS1141: String literal expected.

Of course I could work around this, importing both https and http separately, but I wanted to know if there was a way of fixing the above with a single import?

Without typescript the following works just fine:

const http = require('http'   parseInt(process.env.SSL_ENABLED || '', 10) ? 's' : ''))

CodePudding user response:

This is possible with dynamic import(), which is most convenient when combined with top-level await:

const http = await import(parseInt(process.env.SSL_ENABLED || '', 10) ? 'https' : 'http');
// ...

Beware that dynamic import can have a negative effect on bundlers (since they can't statically analyze the module graph in order to create the bundles), but this looks like Node.js code you probably aren't bundling.

Or if you can't use top-level await for any reason, consume the promise directly:

import(parseInt(process.env.SSL_ENABLED || '', 10) ? 'https' : 'http')
.then(http => {
    // ...use `http` here...
});
  • Related