Search code examples
workbox

How to configure importScript when using vue-cli-pwa plugin


The auto generated service-worker.js import workbox like below:

importScripts("https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js");

As my client may not have the access to googleapis.com, I want to serve the workbox from my server, like the document describe.

importScripts('/third_party/workbox/workbox-sw.js');

workbox.setConfig({
  modulePathPrefix: '/third_party/workbox/'
});

But I can't find a way to configure this from @vue/cli-plugin-pwa.

Extra: the @vue/cli-plugin-pwa is using [email protected], I can not find the matched document. The document serving on google is for version 5.1.2.

File assets

vue.config.js


module.exports = {
    pwa: {
        workboxPluginMode: 'InjectManifest',  // 自定义功能
        workboxOptions: {
          swSrc: './src/sw.js',
          swDest: 'service-worker.js',
        },
    }
}

sw.js

importScripts('/third-party/workbox/workbox-sw.js');
workbox.setConfig({
  modulePathPrefix: '/third-party/workbox/'
});
console.log('hello from service worker');

output:

importScripts("/precache-manifest.247d2cef5fd7daa4fb6945d4ca3b21f4.js", "https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js");

importScripts('/third-party/workbox/workbox-sw.js');
workbox.setConfig({
  modulePathPrefix: '/third-party/workbox/'
});
console.log('hello from service worker');

Solution

  • You can find v4 documentation here, or just read the source code.

    In short, if you still want to use GenerateSW mode:

    module.exports = {
      pwa: {
        workboxOptions: {
          importWorkboxFrom: 'local'
        }
      }
    }