javascriptoffline-cachingsw-toolbox

sw-toolbox script evaluation failed


I'm fiddling around with service workers and want to use sw-toolbox which has a way to support express-style routing. However, when I import it with any version of these lines:

importScripts('node_modules/sw-toolbox/sw-toolbox.js');
importScripts('../node_modules/sw-toolbox/sw-toolbox.js');
importScripts('/node_modules/sw-toolbox/sw-toolbox.js');

I get the following error:

A bad HTTP response code (404) was received when fetching the script.

:3000/node_modules/sw-toolbox/sw-toolbox.js Failed to load resource: net::ERR_INVALID_RESPONSE

Here's my service worker code so far:

(global => {
    'use strict';

    //Load the sw-toolbox library
    importScripts('node_modules/sw-toolbox/sw-toolbox.js');


    //Ensure that our service worker takes control of the page asap
    global.addEventListener('install', event => event.waitUntil(global.skipWaiting()));
    global.addEventListener('activate', event => event.waitUntil(global.clients.claim()));
})(self);

What am I doing wrong?


Solution

  • I'm not sure if this is right, as I didn't find any reference to this in the tutorials on sw-toolbox online, but I found a workaround to get it to import.

    Apparently service workers don't work like module.import, that is, relative to the calling code directory. So I added this script in my server:

      //serve the sw-toolbox
      server.get('/sw-toolbox.js', (req, res) => {
        res.setHeader('Cache-Control', 'no-cache');
        res.setHeader('content-type', 'text/javascript');
        let file = path.join(__dirname,  'node_modules', 'sw-toolbox', 'sw-toolbox.js');
        res.sendFile(file);
      });
    

    And call it from the service worker thusly:

    importScripts('/sw-toolbox.js');
    

    Can anyone explain to me why this works and importScripts doesn't?