astro-sw/README.md
2024-08-17 08:27:49 +02:00

56 lines
No EOL
2.3 KiB
Markdown

# Astro SW
[![Package information: NPM version](https://img.shields.io/npm/v/@ayco/astro-sw)](https://www.npmjs.com/package/@ayco/astro-sw)
[![Package information: NPM license](https://img.shields.io/npm/l/@ayco/astro-sw)](https://www.npmjs.com/package/@ayco/astro-sw)
[![Bundle Size](https://img.shields.io/bundlephobia/minzip/@ayco/astro-sw)](#library-size)
The integration accepts path to your own authored [service worker](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) and automatically injects dynamic variables such as `__assets` generated by Astro for caching. The goal is to let devs retain the flexibility for various [caching strategies](https://developer.chrome.com/docs/workbox/caching-strategies-overview/).
## Installation
In your [Astro](https://astro.build) project:
```bash
# if using npm
$ npm i -D @ayco/astro-sw
# if using pnpm
$ pnpm add -D @ayco/astro-sw
```
## Usage
Example `astro.config.mjs`
```js
import { defineConfig } from "astro/config";
import serviceWorker from "@ayco/astro-sw";
export default defineConfig({
integrations: [
serviceWorker({
path: "./src/sw.js",
})
]
});
```
## API
The integration accepts a configuration object of type `ServiceWorkerConfig` with the following properties
| property | type | required? | notes |
| --- | --- | --- | --- |
| path | string | required | path to your *own* service worker script; no surprises & easy debugging |
| assetCachePrefix | string | optional | cache storage name prefix; useful for debugging |
| assetCacheVersionID | string | optional | cache storage name versioning; by default, a random UUID is used but you can provide your own for easy debugging & invalidation |
| customRoutes | string[] | optional | list of custom routes you want to be cached. Beware that non-existent routes that result to HTTP Error404 will cause the service worker to fail |
| excludeRoutes | string[] | optional | list of routes you want to be ignored/removed from assets |
## Example sw.js
You can find an example service worker (`example_sw.js`) in the [repository](https://ayco.io/gh/astro-sw), and here's the [raw file](https://raw.githubusercontent.com/ayoayco/astro-sw/main/example_sw.js) too.
## Example project
This was developed to support the needs of [Cozy](https://github.com/ayoayco/cozy).