diff --git a/astro.config.mjs b/astro.config.mjs index d9d1628..0ba1893 100644 --- a/astro.config.mjs +++ b/astro.config.mjs @@ -1,11 +1,31 @@ import { defineConfig } from "astro/config"; import node from "@astrojs/node"; +import { readFile, writeFile } from 'node:fs/promises'; +import { fileURLToPath } from 'node:url'; + +let assets = [] // https://astro.build/config export default defineConfig({ output: "server", adapter: node({ mode: "middleware" - }) + }), + integrations: [ + { + 'name': 'astro-cozy-build', + 'hooks': { + 'astro:build:ssr': (options) => { + assets = options.manifest.assets.filter(ass => !ass.includes('sw.js')) + console.log('build-cozy', assets) + }, + 'astro:build:done': async ({dir}) => { + const outFile = fileURLToPath(new URL('./sw.js', dir)); + const originalScript = await readFile(outFile); + await writeFile(outFile, 'const assets = ' + JSON.stringify(assets) + ';' + originalScript); + } + } + } + ] }); \ No newline at end of file diff --git a/public/sw.js b/public/sw.js index 2fcbc7d..c5e1bdc 100644 --- a/public/sw.js +++ b/public/sw.js @@ -70,7 +70,7 @@ self.addEventListener('install', (event) => { event.waitUntil( addResourcesToCache([ './', - './favicon.ico', + ...(assets ?? []) ]) ); }); diff --git a/src/pages/index.astro b/src/pages/index.astro index 039b300..2a0e34d 100644 --- a/src/pages/index.astro +++ b/src/pages/index.astro @@ -48,26 +48,26 @@ navigator.serviceWorker.getRegistrations().then(registrations => { } }); - // const registerSW = async () => { - // if ("serviceWorker" in navigator) { - // try { - // const registration = await navigator.serviceWorker.register("/sw.js", { - // scope: "/", - // }); - // if (registration.installing) { - // console.log("Service worker installing"); - // } else if (registration.waiting) { - // console.log("Service worker installed"); - // } else if (registration.active) { - // console.log("Service worker active"); - // } - // } catch (error) { - // console.error(`Registration failed with ${error}`); - // } - // } else { - // console.log('browser doesn\'t support service workers. boo') - // } - // } + const registerSW = async () => { + if ("serviceWorker" in navigator) { + try { + const registration = await navigator.serviceWorker.register("/sw.js", { + scope: "/", + }); + if (registration.installing) { + console.log("Service worker installing"); + } else if (registration.waiting) { + console.log("Service worker installed"); + } else if (registration.active) { + console.log("Service worker active"); + } + } catch (error) { + console.error(`Registration failed with ${error}`); + } + } else { + console.log('browser doesn\'t support service workers. boo') + } + } - // registerSW(); + registerSW(); \ No newline at end of file