Encountered an issue while trying to register a service worker: "[ERROR] Cannot import statement outside

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',
    },
  },

Answer №1

It seems like the issue lies in the error message you received, stating that the import statement cannot be used in your Service Worker script ('service-worker.js').

Perhaps there was confusion between using import and importScripts? In Service Workers, it is recommended to use the latter. Feel free to include your service-worker.js file in your question for further guidance =)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using ThreeJS in conjunction with NextJS requires that class constructors be called with the 'new' keyword

Seeking assistance with rendering a basic scene within a nextJS route named "lab2". Encountering the following error: Error: class constructors must be invoked with 'new' Call Stack: renderWithHooks mountIndeterminateComponent ...

Preventing Repeated Clicks in AngularJS

Looking for a better approach to handle double clicks in AngularJS other than using ng-disabled. I have a solution to disable double/multi-click functionality on button click and re-enable it after completing an ajax process. Any suggestions? When our cod ...

What sets apart custom events from postMessage?

If you want to send a message to another document, such as an iframe, there are two functions you can use - postMessage and createEvent. Consider the following: var event = document.createEvent('CustomEvent'); event.initCustomEvent("message", tr ...

Include a header in every Apollo query

Looking to add a header to all queries and mutations using Apollo? You might be familiar with the common method: context: { headers: { 'Accept-Language': $this.i18n.current; } } However, this only applies to individual queries or mutatio ...

Updating the DOM with an EventListener in Angular 5 is not functioning properly

Situation : Utilizing an Angular PWA for communication with an iOS native app via WKWebview. Implementing messageHandlers to facilitate data sharing between TypeScript and Swift logic code. Issue : Employing addEventListener to monitor a specific event on ...

changing up the format of nested blockquotes

My website includes various text features, which means that nested blockquotes are a possibility. I am now curious if it is feasible to style nested blockquotes differently from each other! blockquote{ background-color:#666; color:#fff; border ...

Comparison between Mobile Phone's innerWidth and innerHeight Versus Resolution

My test phone, the Galaxy S3 Mini, has a resolution of 800x480 according to its specs. Strangely, when I run the following code in my HTML game: window.innerWidth window.innerHeight The width appears as 533 and the height as 295. I recently discovered ...

Conditions in Controller Made Easy with AngularJS

I have recently started working on implementing a notifications feature. The service will involve making a GET request to a specific URL which will then return an array of notifications. Within the controller, I am in the process of setting up a variable ...

Can a Typescript class type be defined without explicitly creating a JavaScript class?

I am exploring the idea of creating a specific class type for classes that possess certain properties. For example: class Cat { name = 'cat'; } class Dog { name = 'dog'; } type Animal = ???; function foo(AnimalClass: Animal) { ...

The attempt to install myapp using npx create-react-app has failed. The installation has been aborted

Attempting to create a new project using npx create-react-app my-app resulted in an error message saying Aborting installation. https://i.sstatic.net/IhpQJ.jpg Initially, I had node v14.17.1 installed. Upgrading to the latest version 16.4.0 did not resol ...

Adding content to the parent element immediately after it is generated using jQuery

Is there a way to trigger $(e).append() as soon as the element e is created without using setTimeout()? I find that method inefficient. Are there any DOM events that can detect changes in a subtree of a DOM element? Usually, I would just add the code to t ...

Add the component view to the webpage's body section

Using Angular 7 and ngx-bootstrap 4.0.1 Dependencies: "bootstrap": "3.3.7", "bootstrap-colorpicker": "2.5.1", "bootstrap-duallistbox": "3.0.6", "bootstrap-markdown": "2.10.0", "bootstrap-progressbar": "0.9.0", "bootstrap-slider": "9.8.0", "bootstrap-tags ...

Troubleshooting the unsuccessful outcome of the node js async.map function

Context I am new to working with Node.js and the async module. I am encountering difficulties with making synchronous calls to my redis database. Objective My ultimate goal is to return a JSON object when the user calls my REST API's GET method. Th ...

What could be causing the issue of req.body being undefined within the destination function of Multer's diskStorage?

I'm currently utilizing Multer for managing file uploads within my Express.js application. However, I've encountered an issue when attempting to access the req.body values in the destination function of Multer's diskStorage option – it con ...

Latest FF 35 showing alert for blank field in HTML5 email input box

My form includes an email input field with a default value. When the user focuses on the field, it clears out if the value matches the default one. Upon blurring the element, the default value is restored if the field remains empty. In Firefox 35, clickin ...

Parsing JSON data repeatedly using JavaScript within an HTML environment

The following code I found on a popular web development website works perfectly: <!DOCTYPE html> <html> <body> <h1>Customers</h1> <div id="id01"></div> <script> var xmlhttp = new XMLHttpRequest(); var url ...

Issue with ThreeJS CSG when trying to intersect extruded geometries

element, I'm facing a challenge with extracting multiple views and intersecting them to form a final polygon. The issue arises when there are floating extra parts in the result that are unexpected. My goal is to find a solution to detect these extrane ...

Effortless link to a Gremlin database using a JavaScript app

I apologize for my lack of technical knowledge, but I am struggling to solve this issue despite studying the documentation. My goal is to establish a connection with a standard Gremlin DB (Cosmos) using gremlin. While it works well from the server, encoun ...

Change the dropdown header behavior from hovering over it to clicking on it

This snippet of code is integrated into our header to showcase the cart. Currently, the dropdown appears when hovering over it. Is there a way to adjust this so that the dropdown shows up when onclick? <a href="#header-cart" class="skip-link skip-cart ...

Issues with aligning center vertically and horizontally using flexbox are causing unexpected behavior

Understanding the basic concepts of centering a flex container using justify-content:center and align-items: center, I am facing an alignment issue with my box. Can anyone help me with this? This is what I have attempted so far: <template> <di ...