【问题标题】:using WorkerGlobalScope.importScripts() in typescript在打字稿中使用 WorkerGlobalScope.importScripts()
【发布时间】:2019-11-15 16:54:32
【问题描述】:

我正在为(Angular)网络应用程序开发服务人员。这个服务工作者是用 Typescript 制作的。 web-app 应该服务于 service-worker 和一个单独的 configuration.js 文件来配置 pre-build service-worker。

因为每个 web-app 的配置都是唯一的,所以要求配置不直接包含在 service-worker 中。我想为多个网络应用使用同一个 service-worker。

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

给定以下代码,如何在 typescript 中使用 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";
}

如何导入在不同文件中提供的配置?

【问题讨论】:

    标签: typescript import service-worker


    【解决方案1】:

    经过大量额外的搜索/研究,我什么也没发现,我认为目前不可能。

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

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

    虽然这是一个更复杂的解决方案,但它已被证明有效。

    【讨论】:

      猜你喜欢
      • 2017-08-20
      • 2013-08-07
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-10
      • 2021-06-02
      • 2021-03-03
      相关资源
      最近更新 更多