How to generate predefined manifest with versioning using workbox-build for Service Worker

842 views Asked by At

I'm trying to configure workbox-build to create a service worker (generateSW) or inject a manifest (injectManifest) to an existing service worker based on a list of predefined URLs instead of a pattern match in order to preCache specific resources on app load.

not like this:

const { generateSW } = require('workbox-build');

const swDest = 'app/cache-sw.js';
generateSW({
    globDirectory: "app/",
    globPatterns: [
        "**/*.{html,js,png,css,json,txt,ico,config}"
    ]
    swDest
}).then(({ count, size }) => {
    console.log(`Generated ${swDest}, which will precache ${count} files, totaling ${size} bytes.`);
});

but something like this:

const { generateSW } = require('workbox-build');

const swDest = 'app/cache-sw.js';
generateSW({
    globDirectory: "app/",
    manifestURLs: [
        "/index.html",
        "/favicon.ico",
        "/info.txt",
        ...
    ],
    swDest
}).then(({ count, size }) => {
    console.log(`Generated ${swDest}, which will precache ${count} files, totaling ${size} bytes.`);
});

So that the auto-generated service worker contains a manifest similar to something like this:

[
        {
            "url": "/index.html",
            "revision": "487659b6e9c542e7cd8227e0e9d0bed1"
        },
        {
            "url": "/favicon.ico",
            "revision": "29459c5d9c542e7cd8227e0e9d0if83"
        },
        {
            "url": "/info.txt",
            "revision": "73932c5d9c542e7cd8227e0e9z7el19"
        },
        ...
]

And the revision gets updated during build when a resource changes so that the cache is invalidated in the browser on next load.

Thanks in advance!

1

There are 1 answers

2
Jeff Posnick On

A glob pattern without any wildcards should match literal filenames. You should be able to accomplish what you describe by using those filenames as the values passed to globPatterns:

const { generateSW } = require('workbox-build');

const swDest = 'app/cache-sw.js';
generateSW({
    globDirectory: "app/",
    globPatterns: [
        "index.html",
        "favicon.ico",
        "info.txt",
        ...
    ]
    swDest
}).then(({ count, size }) => {
    console.log(`Generated ${swDest}, which will precache ${count} files, totaling ${size} bytes.`);
});