injectServiceWorker plugin should accept callback

This commit is contained in:
RMidhunSuresh 2022-05-18 17:31:17 +05:30
parent 7952a34d64
commit 683ffa9ed3
2 changed files with 16 additions and 2 deletions

View File

@ -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];

View File

@ -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;
}