Reputation: 2231
Scenario
I would like to change my service-worker file from javascript to typescript for better maintenance. Here is my sw.js file:
/* eslint-disable no-console */
self.addEventListener("push", (event) => {
...
});
...more handlers
Problem
I've changed a lot of lines to adapt my code to TS and ESlint requirements, but I have problem with self
I recieve 2 errors from ESlint:
unexpected use of 'self'
self is not defined
How to define self in Typescript file?
Upvotes: 1
Views: 2249
Reputation: 322
you can import webworker lib in sw.ts
/// <reference lib="webworker" />
declare let self: ServiceWorkerGlobalScope;
self.addEventListener('install', () => {
// dosomething
});
Upvotes: 0
Reputation: 2231
In tsconfig.json
file it is needed to add webworker
library
{
....
"compilerOptions": {
"lib": [
...
"webworker"
],...
}
After adding webworker library it is possible to declare self with typescript ServiceWorkerGlobalScope
.
ServiceWorkerGlobalScope interface of the ServiceWorker API represents the global execution context of a service worker.
declare const self: ServiceWorkerGlobalScope;
If you have set isolatedModules
flag to true in you tsconfig.json then you also need to add some import or export directive to your service worker file, because:
Typescript treats files without import/exports as legacy script files. As such files are not modules and any definitions they have get merged in the global namespace. isolatedModules flag forbids such files.
If you do not need any import or export the handies way to make a file a module is add export { };
stack question describing this problem
At the end it is possible to use full typescript syntax in sw.ts
file.
Upvotes: 4