Cyclonecode
Cyclonecode

Reputation: 30071

Dynamic import based on environment variable

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' : ''))

Upvotes: 3

Views: 6185

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074949

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...
});

Upvotes: 2

Related Questions