From 52ecdb9e420bbd596389ca7bb5533ca4a10d1e32 Mon Sep 17 00:00:00 2001 From: Kevin Marrec Date: Tue, 7 Jun 2022 14:57:45 +0200 Subject: [PATCH] fix(workbox): fix worker when using `pages` folder Fixes #11 --- example/nuxt.config.ts | 3 +++ example/{app.vue => pages/index.vue} | 0 src/runtime/workbox/plugin.ts | 14 -------------- src/workbox.ts | 17 +++++++++++------ 4 files changed, 14 insertions(+), 20 deletions(-) rename example/{app.vue => pages/index.vue} (100%) delete mode 100644 src/runtime/workbox/plugin.ts diff --git a/example/nuxt.config.ts b/example/nuxt.config.ts index 59cb74c..ebe4d1f 100644 --- a/example/nuxt.config.ts +++ b/example/nuxt.config.ts @@ -12,6 +12,9 @@ export default defineNuxtConfig({ meta: { // Generate splash screens for iOS mobileAppIOS: true + }, + workbox: { + enabled: true } }, unocss: { diff --git a/example/app.vue b/example/pages/index.vue similarity index 100% rename from example/app.vue rename to example/pages/index.vue diff --git a/src/runtime/workbox/plugin.ts b/src/runtime/workbox/plugin.ts deleted file mode 100644 index f36339c..0000000 --- a/src/runtime/workbox/plugin.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { joinURL } from 'ufo' -import { defineNuxtPlugin, useRuntimeConfig } from '#app' - -export default defineNuxtPlugin(() => { - if ('serviceWorker' in navigator) { - const { baseURL } = useRuntimeConfig().app - - window.addEventListener('load', () => { - navigator.serviceWorker.register( - joinURL(baseURL, 'sw.js') - ) - }) - } -}) diff --git a/src/workbox.ts b/src/workbox.ts index ea6b12b..8d15871 100644 --- a/src/workbox.ts +++ b/src/workbox.ts @@ -1,6 +1,7 @@ -import { join } from 'pathe' -import { addPlugin, addTemplate, useNuxt } from '@nuxt/kit' +import { addTemplate, useNuxt } from '@nuxt/kit' import consola from 'consola' +import { join } from 'pathe' +import { joinURL } from 'ufo' import type { PWAContext } from './types' export default (pwa: PWAContext) => { @@ -8,6 +9,7 @@ export default (pwa: PWAContext) => { const options = pwa.workbox const nuxt = useNuxt() + const head = nuxt.options.app.head as Required // Warning when in development mode if (nuxt.options.dev) { @@ -27,9 +29,12 @@ export default (pwa: PWAContext) => { options }) - // Plugin that registers the Service Worker - addPlugin({ - src: pwa._resolver.resolve('./runtime/workbox/plugin'), - mode: 'client' + // Embed script that registers the Service Worker + head.script.push({ + children: [ + "if ('serviceWorker' in navigator) {", + ` window.addEventListener('load', () => navigator.serviceWorker.register('${joinURL(nuxt.options.app.baseURL, 'sw.js')}'))`, + '}' + ].join('\n') }) }