From 683ffa9ed376ae3d5197c6dda5789db2588b33dc Mon Sep 17 00:00:00 2001 From: RMidhunSuresh Date: Wed, 18 May 2022 17:31:17 +0530 Subject: [PATCH] injectServiceWorker plugin should accept callback --- scripts/build-plugins/service-worker.js | 3 ++- vite.config.js | 15 ++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/scripts/build-plugins/service-worker.js b/scripts/build-plugins/service-worker.js index 805f6000..85619545 100644 --- a/scripts/build-plugins/service-worker.js +++ b/scripts/build-plugins/service-worker.js @@ -8,7 +8,7 @@ function contentHash(str) { return hasher.digest(); } -function injectServiceWorker(swFile, otherUnhashedFiles, placeholdersPerChunk) { +function injectServiceWorker(swFile, findUnhashedFileNamesFromBundle, placeholdersPerChunk) { const swName = path.basename(swFile); let root; let version; @@ -31,6 +31,7 @@ function injectServiceWorker(swFile, otherUnhashedFiles, placeholdersPerChunk) { logger = config.logger; }, generateBundle: async function(options, bundle) { + const otherUnhashedFiles = findUnhashedFileNamesFromBundle(bundle); const unhashedFilenames = [swName].concat(otherUnhashedFiles); const unhashedFileContentMap = unhashedFilenames.reduce((map, fileName) => { const chunkOrAsset = bundle[fileName]; diff --git a/vite.config.js b/vite.config.js index 362f8f81..53a7f452 100644 --- a/vite.config.js +++ b/vite.config.js @@ -37,7 +37,7 @@ export default defineConfig(({mode}) => { // important this comes before service worker // otherwise the manifest and the icons it refers to won't be cached injectWebManifest("assets/manifest.json"), - injectServiceWorker("./src/platform/web/sw.js", ["index.html", "assets/config.json", "assets/theme-element.json"], { + injectServiceWorker("./src/platform/web/sw.js", findUnhashedFileNamesFromBundle, { // placeholders to replace at end of build by chunk name index: { DEFINE_GLOBAL_HASH: definePlaceholders.DEFINE_GLOBAL_HASH, @@ -48,3 +48,16 @@ export default defineConfig(({mode}) => { define: definePlaceholders, }); }); + +function findUnhashedFileNamesFromBundle(bundle) { + const names = ["index.html"]; + for (const fileName of Object.keys(bundle)) { + if (fileName.includes("config.json")) { + names.push(fileName); + } + if (/theme-.+\.json/.test(fileName)) { + names.push(fileName); + } + } + return names; +}