2

In webpack most of my filenames are appended a content hash, e.g. 'app.bfu98y98UB899UHhi9q.js' This presents a problem because in my service worker file i need to add a list of all the filenames that will be cached but all the filenames will not be known until after build. Now, i discovered webpack manifest plugin which emits a json file that contains a list of transformed file names. So i thought great now i can just import the json into my service worker, but then i found out you cannot import json into service workers. So now i am stuck not knowing how to give my service worker the list of hashed file names. I am aware that there are some plugins like the workbox plugin that handle all of this for you but i would like to know how i can accomplish this without such a plugin. Any help appreciated, thanks

1 Answer 1

0

I was able to solve this by creating a custom plugin that emits a javascript file that contains a function that adds all of the output hashed file names into an array. Then i use the the method importScripts(file) (since regular imports are not allowed in service workers) present on WorkerGlobalScope to access the function that returns the array with the hashed file names. The custom plugin looks like this:

function FilesListPlugin() {}
FilesListPlugin.prototype.apply = compiler => {
  compiler.hooks.emit.tapAsync('FileListPlugin', (compilation, callback) => {
    const filelist = Object.keys(compilation.assets).map(fileName => '${fileName}'`);
    compilation.assets['filesList.js'] = {
      source: () => `const getFilesList = () => [${filelist}]`,
      size: () => filelist.length,
    };
    callback();
  });
};

then i just imported the plugin into the webpack plugins array and called the file with importScripts('filesList.js') inside the service worker so that the getFilesList() method i created is visible. This is using webpack v.5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.