在打字稿中使用WorkerGlobalScope.importScripts()

我正在为(Angular)网络应用服务。该服务人员是用Typescript制作的。该Web应用程序应为服务工作者提供服务,并提供一个单独的configuration.js文件来配置预构建的服务工作者。

由于每个Web应用程序的配置都是唯一的,因此要求该配置不直接包含在服务工作者中。我想为多个Web应用程序使用同一服务人员。

使用WorkerGlobalScope.importScripts()可以将外部资源导入服务人员的全局范围。但是,它将如何与打字稿一起使用?

给出以下代码,如何在打字稿中使用importScripts()

interface IConfiguration {
    name: string;
}

let configuration: IConfiguration;

const initialize = (service: ServiceWorkerGlobalScope): void => {
    service.addEventListener("install",(event) => {
        console.log("Installing Service-Worker");

        service.importScripts("SWConfiguration.js");
        configuration = new service.SWConfiguration()  // <-- This won't compile

        return service.skipWaiting();
    });

    service.addEventListener("activate",(event) => {
        console.log("activating Service-Worker");
        event.waitUntil(service.clients.claim());
    });

    service.addEventListener("fetch",(event) => {

        // Do something with the configuration

    });
};

initialize(self as any);

SWConfiguration.js类似于:

public class SWConfiguration {
    name = "myName";
}

如何导入另一个文件中提供的配置?

dibatian 回答:在打字稿中使用WorkerGlobalScope.importScripts()

经过大量其他搜索/研究后,我什么都没发现,我认为目前尚不可能。

我研究了Angular Service-Worker的工作原理以及如何加载其配置(使用JSON格式配置)。该服务人员将仅尝试从/ngsw.json获取文件,并将结果配置写入IndexedDB。 他们还使用哈希进行一些版本检查。 Angular SW configurator 您可以在第693行看到请求;

this.safeFetch(this.adapter.newRequest('ngsw.json?ngsw-cache-bust=' + Math.random()));

虽然这是一个更复杂的解决方案,但事实证明它是可行的。

本文链接:https://www.f2er.com/3123054.html

大家都在问