繁体   English   中英

在函数中使用动态导入时,如何在全局变量中指定类型信息?

[英]When using dynamic import in a function, how can I specify type info in global variable?

我的简化服务器代码如下所示。

服务器.ts

import google from "googleapis";

const androidPublisher = google.androidpublisher("v3");

app.use('something', function(req, res, n){
   ...
})

...(only one of the dozens of other methods use androidPublisher)

我正在导入googleapis库以设置androidpublisher变量。 但是,这个googleapis库很大,完全导入文件需要400ms~700ms,而导入其他库文件需要10ms~30ms。

因为我的环境是无服务器架构(firebase 函数),并且因为大约 100 个请求中有 1 个实际上需要androidPublisher ,所以我想在必要时利用动态导入来导入googleapis 否则,即使androidPublisher ,上述设置实际上也会为启动新的无服务器实例的每个请求增加 400 毫秒/700 毫秒的延迟。

所以我做了如下改变。

服务器.ts

let androidPublisherInstance:any;

async function getAndroidPublisher() {
    const googleapis = await import("googleapis");

    if (androidPublisherInstance === undefined) {
        const ap = googleapis.google.androidpublisher("v3");
        androidPublisherInstance = ap;
    }
    return androidPublisherInstance;
}


...(one of methods use getAndroidPublisher() to get androidPublisher instance)

在上面的设置中,我仅在需要时使用全局变量和辅助函数来初始化 androidPublisher。 这按预期工作,并且在第一次需要 androidPublisher 时会添加 400 毫秒~700 毫秒的延迟。 但是,我最终将androidPublisherInstance类型设为any 我无法正确定义类型,因为类型定义在googleapis内部可用,并且驻留在getAndroidPublisher函数内部。

因此,当我使用androidPublisherInstance时,我失去了使用androidPublisherInstance所有好处,并且必须在使用方法/属性的同时玩猜谜游戏。

而且我认为我必须使用全局变量,因为我不想在函数调用getAndroidPublisher()时多次初始化 androidPublisher ( googleapis.google.androidpublisher("v3") getAndroidPublisher()

我错过了什么吗? 有没有办法使用动态导入并让客户端只初始化一次而无需使用全局变量?

您可以只导入类型。 只要你只在类型定义中使用它,而不是在值表达式中使用它,编译后的 JavaScript 就永远不会加载模块:

import { androidpublisher_v3 } from "googleapis";
let androidpublisher: androidpublisher_v3 | undefined;

或者,为了确保您不会意外在错误的地方引用它,请仅使用导入类型

let androidpublisher: import("googleapis").androidpublisher_v3 | undefined;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM