Angular: Using TypeScript for Service Worker (ServiceWorkerModule)

99封情书 提交于 2020-01-25 06:55:10

问题


Is it possible to register a ServiceWorker written in TypeScript with @angular/service-worker?

currently registering a service worker looks like this in app.module.ts:

ServiceWorkerModule.register('ngsw-worker.js', {
  enabled: environment.production
})

Is it somehow possible to register a ngsw-worker.ts?

At least this is possible with web workers in Angular:

const worker = new Worker('../my-worker.worker', {
      type: 'module'
    });

my-worker.worker.ts

/// <reference lib="webworker" />

import {someMethod} from './some-method';

addEventListener('message', ({ data }) => {
  const response = `worker response to ${data}`;
  postMessage(response);
  someMethod();
});

Any help is appreciated - thanks


回答1:


Ofcourse it is possible to rewrite anything in js in typescript. But to run it in browser you will have to compile it into JavaScript. As, browser doesn't interpret/understand typescript as of now.

To do so, you can use typescript command: tsc .

In your package.json, create a script command like this:-

"scripts": {
    "compile-to-ts": "tsc my-service-worker.ts"
}

Now run above command as:-

npm run compile-to-ts

It will compile your typescript file into javascript and place the generated file in a directory based on tsconfig file.

UPDATE: You can also use type definition of service worker from here . You can utilize this to improve type safety in your service worker typescript code and avoid any typescript related error(if any).




回答2:


As a beginner with Angular/TypeScript/Javascript I've tried the same for a few days. My intents were to use TypeScript as my main language to use it as an es5 transpiler, so I don't have to worry about:

  • language versioning (es5, es2015, ...)
  • bundling
  • linting
  • etc

And I think I've got a nice, yet weird solution with uses the worker-plugin, available starting with Angular8.

Example:

workers/service-worker.worker.ts

// Import angular serviceworker
importScripts("ngsw-worker.js");

// custom code
addEventListener("message", (data) => {
    console.log(data);
});

workers/service-worker-config.ts

import { environment } from "../../environments/environment";

export let generatedServiceWorkerUrl: string = null;
(function generateUrl(): void {
    // Override the real Worker with a stub
    // to return the filename, which will be generated/replaced by the worker-plugin.
    // @ts-ignore
    Worker = class WorkerStub {
        constructor(public stringUrl: string, public options?: WorkerOptions) {}
    };

    const worker = new Worker("./service-worker.worker", { type: "module" }) as any;
    generatedServiceWorkerUrl = worker.stringUrl;
})();

export const serviceWorkerConfig = {
    enabled: environment.production,
    serviceWorkerUrl: generatedServiceWorkerUrl
};

app.module.ts

import { serviceWorkerConfig  } from "./workers/service-worker-config";

@NgModule({
    declarations: [AppComponent],
    entryComponents: [],
    imports: [
        [...],
        ServiceWorkerModule.register(serviceWorkerConfig.serviceWorkerUrl, { enabled: serviceWorkerConfig.enabled })
    ],
    providers: [...],
    bootstrap: [AppComponent]
})
export class AppModule {}


来源:https://stackoverflow.com/questions/57238882/angular-using-typescript-for-service-worker-serviceworkermodule

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!