Search code examples
reactjsviteservice-worker

Service worker not registering on vite react app


For a while now I have been trying to register service worker for my vite react app but for some odd reason it not registering in production environment, while it does on localhost.

Below is my vite configuration:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
import svgr from "vite-plugin-svgr";

export default defineConfig({
  plugins: [react(), svgr()],
  build: {
    outDir: "build",
    rollupOptions: {
      external:['./service-worker.js'],
      output: {
        manualChunks(id) {
          if (id.includes("node_modules")) {
            return "vendor";
          }
        },
      },
    },
  },
  server: {
    hmr:{
overlay: false,
    },
    proxy: {
      "/api": {
        target: "http://localhost:8000",
        changeOrigin: true,
        secure: false,
        ws: true,
        logLevel: "debug",
        onProxyReq: function (proxyReq, req, res) {
          proxyReq.setHeader("Content-Length", req.body.length);
        },
      },
    },
  },
});

I have tried registering it in my app entry point, calling the service worker file from the root directory, but it's not working.


Solution

  • You have incorrectly used the rollupOptions.external.

    external just means vite will ignore it and not put it in the output directory.

    If what you want is to have your service-worker.js in your output directory, you can use the vite-plugin-static-copy plugin: https://www.npmjs.com/package/vite-plugin-static-copy

    import { viteStaticCopy } from 'vite-plugin-static-copy'
    
    export default defineConfig({
      plugins: [
        viteStaticCopy({
          targets: [
            {
              src: './service-worker.js', // correct path to this file.
              dest: './', // root of your output directory
            },
          ],
        }),
      ]
    })