Search code examples
javascriptregexworkbox

Workbox routing for images in subfolders


I am using workbox to manage the caching of my assets, which works great.

I am having 1 or 2 issues with regular expressions when caching my images:

I am trying to cache all images in the images folder & icons subfolder (image of folder structure below)

I have tried the following to try and cache the images:

workbox.routing.registerRoute(
  /images\/.(?:png|gif|jpg|jpeg|svg|ico|webp)$/,  //<-- Regexp
  workbox.strategies.cacheFirst({
   cacheName: 'images',
   plugins: [
    new workbox.expiration.Plugin({
      maxEntries: 100,
      maxAgeSeconds: 60 * 60 * 24 * 365
    }),
  ],
 }),
);

//I also tried a regexp on the entire images folder
workbox.routing.registerRoute(
  new RegExp('^/images/'),    //<-- Regexp
  workbox.strategies.cacheFirst({
    cacheName: 'images',
    plugins: [
      new workbox.expiration.Plugin({
        maxEntries: 100,
        maxAgeSeconds: 60 * 60 * 24 * 365
      }),
    ],
  }),
);

I included the code samples above to give context to what I am trying to achieve

Any help would be appreciated!

Folder Structure:

enter image description here


Solution

  • There are a few different ways that you can define routes in Workbox. While you can pass in a RegExp as the first parameter to registerRoute(), like you're doing, you could instead pass in a matchCallback function, which can examine the incoming request and return either a "truthy" or false value depending on whether you want the route to trigger.

    There's a recipe in the Workbox docs for setting up a route based on the request.destination value, which for subresources being used as images on your page, will be 'image'. You could combine that with a check of the url.pathname inside of your matchCallback if you want to limit your route so that it only matches images within a certain subfolder.

    So, taken together, it would look something like:

    workbox.routing.registerRoute(
      ({request, url}) => request.destination === 'image' &&
                          url.pathname.startsWith('/images'),
      workbox.strategies.cacheFirst({
        cacheName: 'images',
        plugins: [
          new workbox.expiration.Plugin({
            maxEntries: 100,
            maxAgeSeconds: 60 * 60 * 24 * 365
          }),
        ],
      })
    );