0

在一个项目中,我有一个环境变量,应该用于指定我们是否要使用 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' : ''))
4

1 回答 1

1

这可以通过dynamic实现,与import()top-levelawait结合使用时最方便:

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

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

await或者,如果您出于任何原因不能使用顶级,请直接使用承诺:

import(parseInt(process.env.SSL_ENABLED || '', 10) ? 'https' : 'http')
.then(http => {
    // ...use `http` here...
});
于 2021-11-13T11:37:02.037 回答