From 54f020b16515add306462b3016e8780cfcbe5795 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 12 Feb 2023 15:48:56 +0100 Subject: [PATCH] fix: use nitro `publicAssets` to emit manifests --- modules/pwa/index.ts | 40 ++++++++++++++++++++++------------------ 1 file changed, 22 insertions(+), 18 deletions(-) diff --git a/modules/pwa/index.ts b/modules/pwa/index.ts index 08feafdf..f68b4fe6 100644 --- a/modules/pwa/index.ts +++ b/modules/pwa/index.ts @@ -1,7 +1,9 @@ +import { mkdir, writeFile } from 'node:fs/promises' import { defineNuxtModule } from '@nuxt/kit' import type { VitePluginPWAAPI } from 'vite-plugin-pwa' import { VitePWA } from 'vite-plugin-pwa' import type { Plugin } from 'vite' +import { join } from 'pathe' import type { VitePWANuxtOptions } from './types' import { configurePWAOptions } from './config' import { type LocalizedWebManifest, createI18n, pwaLocales } from './i18n' @@ -26,6 +28,13 @@ export default defineNuxtModule({ nuxt.options.appConfig = nuxt.options.appConfig || {} nuxt.options.appConfig.pwaEnabled = !options.disable + nuxt.options.nitro.publicAssets = nuxt.options.nitro.publicAssets || [] + const manifestDir = join(nuxt.options.buildDir, 'manifests') + nuxt.options.nitro.publicAssets.push({ + dir: manifestDir, + baseURL: '/', + maxAge: 0, + }) // TODO: combine with configurePWAOptions? nuxt.hook('nitro:init', (nitro) => { options.outDir = nitro.options.output.publicDir @@ -50,24 +59,19 @@ export default defineNuxtModule({ throw new Error(`No webmanifest found for locale/theme ${entry}`) return JSON.stringify(manifest) } - viteInlineConfig.plugins.push({ - name: 'elk:pwa:locales:build', - apply: 'build', - generateBundle(_, bundle) { - if (options.disable || !bundle) - return - - Object.keys(webmanifests!).map(wm => [wm, `manifest-${wm}.webmanifest`]).forEach(([wm, fileName]) => { - bundle[fileName] = { - needsCodeReference: false, - type: 'asset', - name: undefined, - source: generateManifest(wm), - fileName, - } - }) - }, - }) + if (isClient) { + viteInlineConfig.plugins.push({ + name: 'elk:pwa:locales:build', + apply: 'build', + async writeBundle(_options, bundle) { + if (options.disable || !bundle) + return + await mkdir(manifestDir, { recursive: true }) + for (const wm in webmanifests) + await writeFile(join(manifestDir, `manifest-${wm}.webmanifest`), generateManifest(wm)) + }, + }) + } viteInlineConfig.plugins.push({ name: 'elk:pwa:locales:dev', apply: 'serve',