Skip to content

Instantly share code, notes, and snippets.

@JonDotsoy
Last active September 26, 2023 14:30
Show Gist options
  • Save JonDotsoy/4582bc119643411eca6032c3eb2b7245 to your computer and use it in GitHub Desktop.
Save JonDotsoy/4582bc119643411eca6032c3eb2b7245 to your computer and use it in GitHub Desktop.
How to write a Service Worker with Astro.build

How to write a service worker with Astro.build

Astro.build is a web framework for building websites, and it also enables you to create Progressive Web Apps (PWAs). One of Astro's powerful features is its ability to import and compile scripts at runtime.

Let's take a look at the following sample:

<script>
  import "../scripts/script.js"
</script>

In this example, we utilize the <script> tag to import a local file ("../scripts/script.js"). Astro compiles this file and makes it available for use in the browser.

You can leverage this feature to declare a Service Worker file. However, instead of using import(path), you should use import.meta.resolve(path). You should also register the service worker with ServiceWorkerContainer.register, like so:

You can leverage this feature to declare a Service Worker file. Hovever, instead of using import(path), you should use import.meta.resolve(path). You should also register the service worker with ServiceWorkerContainer.register, like so:

<script>
  const swPath = import.meta.resolve("../scripts/sw.ts");
  
  await navigator.serviceWorker.register(swPath, {
    type: "module",
  });
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment