With the utilization of register-service-worker
, the boilerplate for registerServiceWorker
remained untouched.
/* eslint-disable no-console */
import { register } from 'register-service-worker';
if (process.env.NODE_ENV === 'production') {
register(`${process.env.BASE_URL}service-worker.js`, {
ready() {
console.log(
'App is being served from cache by a service worker.\n'
);
},
registered() {
console.log('Service worker has been registered.');
},
cached() {
console.log('Content has been cached for offline use.');
},
updatefound() {
console.log('New content is downloading.');
},
updated() {
console.log('New content is available; please refresh.');
},
offline() {
console.log('No internet connection found. App is running in offline mode.');
},
error(error) {
console.error('Error during service worker registration:', error);
},
});
}
After attempting yarn build
for production, all seemed to be in order. However, upon deployment or testing on localhost, an error surfaced:
Cannot use import statement outside a module
in service-worker.js
I thought about adding <type="module">
under script as a workaround. But in the context of a vue-project, it's not very practical. Any suggestions on how to resolve this issue? Below is my configuration for PWA in vue.config.js
:
// vue.config.js
pwa: {
manifestOptions: {
background_color: '#f2f2f2',
purpose: 'maskable any',
},
// configure the workbox plugin
workboxPluginMode: 'InjectManifest',
workboxOptions: {
// swSrc is required in InjectManifest mode.
swSrc: 'src/registerServiceWorker.js',
swDest: 'service-worker.js',
},
},