2

I have a react tsx project set up already. I am attempting to make it a PWA. In order to do this I need to add service workers. I added service workers in the src folder but am receiving this error when I run firebase deploy

The script has an unsupported MIME type ('text/html'). react_devtools_backend_compact.js:2367 Service Worker registration failed: DOMException: Failed to register a ServiceWorker for scope ('/') with script.... The script has an unsupported MIME type ('text/html').

I am hosting my app on firebase

this is my index.tsx in the src folder

 import React from "react"
import ReactDOM from "react-dom/client"
import "./index.css"
import App from "./App"
import reportWebVitals from "./reportWebVitals"
import * as serviceWorker from "./serviceWorker"

// import "bootstrap/dist/css/bootstrap.min.css"
// import { AuthProvider } from "./AuthContext"

const root = ReactDOM.createRoot(document.getElementById("root") as HTMLElement)
root.render(
  <React.StrictMode>
    {/* <AuthProvider> */}
    <App />
    {/* </AuthProvider> */}
  </React.StrictMode>
)
serviceWorker.register()

reportWebVitals()

this is my serviceWorker.js file

export function register() {
  if ("serviceWorker" in navigator) {
    window.addEventListener("load", () => {
      navigator.serviceWorker
        .register("/service-worker.js")
        .then((registration) => {
          console.log("Service Worker registered with scope:", registration.scope)
        })
        .catch((error) => {
          console.error("Service Worker registration failed:", error)
        })
    })
  }
}

export function unregister() {
  if ("serviceWorker" in navigator) {
    navigator.serviceWorker.ready
      .then((registration) => {
        registration.unregister()
      })
      .catch((error) => {
        console.error("Service Worker unregistration failed:", error)
      })
  }
}
   

this is my manifest json file

{
  "name": "Your App",
  "short_name": "your-app",
  "description": "fun app to use",
  "start_url": "/",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#007bff",
  "icons": [
    {
      "src": "./app-icon.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "./app-icon.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ]
}

I first do npm run build and then firebase deploy. Then I see the error. Any clarity on this would be helpful.

The manifest.json file and the serviceWorker file are both in the same src folder as the index.tsx file.

1 Answers1

0

I transferred the service worker to the public folder This is my updated index.html in the public folder

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta name="description" content="Web site created using create-react-app" />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <script>
      if ("serviceWorker" in navigator) {
        window.addEventListener("load", function () {
          navigator.serviceWorker
            .register("Serviceworker.js")
            .then(
              function (registration) {
                console.log("Worker registration successful", registration.scope)
              },
              function (err) {
                console.log("Worker registration failed", err)
              }
            )
            .catch(function (err) {
              console.log(err)
            })
        })
      } else {
        console.log("Service Worker is not supported by browser.")
      }
    </script>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>

This is my Serviceworker.js in the public folder.

var CACHE_NAME = "pwa-task-manager"
var urlsToCache = ["/", "/completed"]

// Install a service worker
self.addEventListener("install", (event) => {
  // Perform install steps
  event.waitUntil(
    caches.open(CACHE_NAME).then(function (cache) {
      console.log("Opened cache")
      return cache.addAll(urlsToCache)
    })
  )
})

// Cache and return requests
self.addEventListener("fetch", (event) => {
  event.respondWith(
    caches.match(event.request).then(function (response) {
      // Cache hit - return response
      if (response) {
        return response
      }
      return fetch(event.request)
    })
  )
})

// Update a service worker
self.addEventListener("activate", (event) => {
  var cacheWhitelist = ["pwa-task-manager"]
  event.waitUntil(
    caches.keys().then((cacheNames) => {
      return Promise.all(
        cacheNames.map((cacheName) => {
          if (cacheWhitelist.indexOf(cacheName) === -1) {
            return caches.delete(cacheName)
          }
          return null // Return a value for each iteration
        })
      )
    })
  )
})