Angular 角度:为服务工作者(ServiceWorkerModule)使用TypeScript

Angular 角度:为服务工作者(ServiceWorkerModule)使用TypeScript,angular,typescript,service-worker,angular-service-worker,Angular,Typescript,Service Worker,Angular Service Worker,是否可以向@angular/service worker注册用TypeScript编写的服务人员 当前在app.module.ts中注册服务工作人员的情况如下所示: ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production }) 是否有可能注册一个ngsw worker.ts 至少在以下情况下,web工作人员可以做到这一点: const worker = new Worker('../m

是否可以向
@angular/service worker
注册用TypeScript编写的服务人员

当前在app.module.ts中注册服务工作人员的情况如下所示:

ServiceWorkerModule.register('ngsw-worker.js', {
  enabled: environment.production
})
是否有可能注册一个
ngsw worker.ts

至少在以下情况下,web工作人员可以做到这一点:

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

//
从“./someMethod”导入{someMethod};
addEventListener('消息',({data})=>{
const response=`worker对${data}的响应`;
后消息(响应);
somethod();
});

非常感谢您的帮助,当然可以用typescript重写js中的任何内容。但要在浏览器中运行它,您必须将其编译为JavaScript。如前所述,浏览器目前无法解释/理解typescript

为此,可以使用typescript命令:tsc

在package.json中,创建如下脚本命令:-

"scripts": {
    "compile-to-ts": "tsc my-service-worker.ts"
}
现在以如下方式运行上述命令:-

npm run compile-to-ts
它将把typescript文件编译成javascript,并将生成的文件放在基于tsconfig文件的目录中


更新:您还可以从中使用服务人员的类型定义。您可以利用它来提高服务人员typescript代码中的类型安全性,并避免任何与typescript相关的错误(如果有)。

作为Angular/typescript/Javascript的初学者,我已经尝试了几天了。 我打算使用TypeScript作为我的主要语言,将其用作es5 transpiler,因此我不必担心:

  • 语言版本控制(es5、es2015等)
  • 捆绑
  • 皮棉
我想我已经有了一个很好但很奇怪的解决方案,它使用了worker插件,可以从Angular8开始使用

例如:

工人/服务工人.worker.ts

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

// custom code
addEventListener("message", (data) => {
    console.log(data);
});
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
};
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 {}
工人/服务工人配置.ts

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

// custom code
addEventListener("message", (data) => {
    console.log(data);
});
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
};
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 {}
应用程序模块.ts

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

// custom code
addEventListener("message", (data) => {
    console.log(data);
});
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
};
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 {}

浏览器不知道类型脚本。TypeScript被编译成JavaScript,这就是浏览器下载和执行的内容:JavaScript代码,而不是TypeScript代码。是的,但是Angular在内部使用webpack将这些TS文件编译成JS。为什么不也针对服务工作者,因为他们已经支持web工作者了?AFAIR,此代码用于注册Angular服务工作者,由Angular编写和提供。为什么要重写它?我想在软件和主线程上使用方法(TS文件)。我目前的方法是在单独的构建步骤中绑定它们,并通过
importScripts('sw-bundle.js')
导入它们。我的问题是,是否有更好的方法来实现这一点,例如,使用角度编译器。它适用于web工作人员(使用上面的代码),我也希望使用类似的软件。但您是对的,它看起来像
ServiceWorkerContainer.register
只是从Angular模块调用而已,但如果我的
my service worker.ts
正在从其他ts文件导入内容(如上面的某种方法)需要像webpack或rollup这样的捆绑包。这是我想要避免的一步,让Angular编译器处理这个问题。这非常好!它既允许自定义代码,也允许通过
ng serve
Angular 10的更新来测试您的服务工作,正如在生产中一样,
generateUrl
功能将被删除(显然是因为它没有直接引用)。直接调用它可以解决此问题,例如,使
generateUrl
返回URL,然后使用
serviceworUrl:generateUrl()
将其保存在配置中。