基于环境变量的动态导入

Dynamic import based on environment variable

在一个项目中,我有一个环境变量,用于指定我们是否要使用 HTTPS:

SSL_ENABLED=1

基于这个环境变量,我现在尝试使用 https 或 http 模块:

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

const server = http.createServer(...)

上面的导入抛出以下打字稿错误:

TS1141: String literal expected.

当然我可以解决这个问题,分别导入 https 和 http,但我想知道是否有一种方法可以通过一次导入来解决上述问题?

没有打字稿,以下工作正常:

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

这可以通过 dynamic import(), which is most convenient when combined with top-level await:

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

注意动态导入会对捆绑器产生负面影响(因为它们无法静态分析模块图以创建捆绑包),但这看起来像 Node.js 您可能不是的代码捆绑。

或者如果您出于任何原因无法使用顶级 await,请直接使用 promise:

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