Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is there a way to use sw without using precache? #302

Closed
ZYinMD opened this issue Jun 8, 2022 · 17 comments
Closed

Is there a way to use sw without using precache? #302

ZYinMD opened this issue Jun 8, 2022 · 17 comments

Comments

@ZYinMD
Copy link
Contributor

ZYinMD commented Jun 8, 2022

(I'm using injectManifest)

In my app, I need to use sw to intercept and modify traffic, but I don't need precaching (in fact, precaching leads to various troubles in my case).

So, I removed precacheAndRoute(self.__WB_MANIFEST) from my sw source code, then I got this error when building:

error during build:
Error: Unable to find a place to inject the manifest. 
This is likely because swSrc and swDest are configured to the same file. 
Please ensure that your swSrc file contains the following: self.__WB_MANIFEST
  
at injectManifest (node_modules\workbox-build\build\inject-manifest.js:77:19)
at async generateInjectManifest (node_modules\vite-plugin-pwa\dist\index.js:244:23)
at async _generateSW (node_modules\vite-plugin-pwa\dist\index.js:634:7)
at async Object.closeBundle (node_modules\vite-plugin-pwa\dist\index.js:683:11)

Is there a way to use workbox routing strategies without using precache? Thanks!

@userquin
Copy link
Member

userquin commented Jun 8, 2022

You only need the injection point, just assign it to a const variable, dont use it and you are done.

About usage of workbox you shoukd ask on workbox repo, just check the links on the docs there are some examples on their docs website

@userquin
Copy link
Member

userquin commented Jun 8, 2022

@ZYinMD
Copy link
Contributor Author

ZYinMD commented Jun 8, 2022

Hi @userquin, thanks, I'm confused about the "just assign it to a const variable and dont use it" that you said. In which file do I do that, and who is it?

I assume I'll still use the same setup of the VitePWA plugin in vite config? And I assume I'll still use the same registerSW() from virtual:pwa-register?

I tried to put self.__WB_MANIFEST = [] or precacheAndRoute([]) in my sw source, but that didn't work, guess it's not what you meant.

@userquin
Copy link
Member

userquin commented Jun 8, 2022

// sw.ts => your service worker
const wbManifest = self.__WB_MANIFEST
// use another strategies without using wbManifest 
// you don't need to use precacheAndRoute

The registerSW must be imported/used on your main jsx/js/ts/tsx.

The error you get comes from workbox-build since there is no self.__WB_MANIFEST (the injection point): you remove the entire line and you should have it.

Maybe in a future we can just build the custom service worker without using workbox-build::injectRegister function (via some new configuration option or using a new strategy).

@ZYinMD
Copy link
Contributor Author

ZYinMD commented Jun 8, 2022

Hi @userquin, thanks, not sure if I understood you correctly, but if I leave everything unchanged, and only make the one-line change you suggested, it won't compile:

// sw.ts
import { precacheAndRoute } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';

precacheAndRoute(self.__WB_MANIFEST); // does compile
registerRoute(myRoute);

into ↓

// sw.ts
import { registerRoute } from 'workbox-routing';

const wbManifest = self.__WB_MANIFEST; // does not compile
registerRoute(myRoute);

Searching "wbManifest" in this repo doesn't yield any match. Did you mean another spelling?

@userquin
Copy link
Member

userquin commented Jun 8, 2022

@ZYinMD check this repo, it is building a custom sw for serving dynamic pages: the sw is here https://github.com/userquin/test-pwa-ts-4.5.5/blob/main/src/sw.ts

You can check it deployed at netlify here: https://optimistic-cray-38ef22.netlify.app/

@ZYinMD
Copy link
Contributor Author

ZYinMD commented Jun 8, 2022

Hi @userquin, thanks, I thought we were talking about how to use sw without using precache? But the sw.ts you linked does contain precacheAndRoute(self.__WB_MANIFEST).

I also went to the production site, when I reload, I see both index.html and many other static asset files are served from precache.

@userquin
Copy link
Member

userquin commented Jun 8, 2022

@ZYinMD my sw is using the const wbManifest = self.__WB_MANIFEST;, if you call registerRoute(myRoute); without calling precacheAndRoute will throw an error on runtime not in build time, just read the comments on my custom sw.

EDIT: I mean, if you're not using precacheAndRoute you cannot use registerRoute since it will check if matched on the global precache entry IIRC.

@userquin
Copy link
Member

userquin commented Jun 8, 2022

@ZYinMD you should ask on workbox repo instead here

@ZYinMD
Copy link
Contributor Author

ZYinMD commented Jun 9, 2022

Thanks, after some reading, I've come to the conclusion that both generateSW and injectManifest are designed to handle precache. If I don't need precache, I should just use a bundler to compile my sw.ts, then register it manually with navigator.serviceWorker.register("sw.js"). I'll probably just use esbuild to do that as part of my build process, and remove vite-plugin-pwa.

@ZYinMD ZYinMD closed this as completed Jun 9, 2022
@victordidenko
Copy link

victordidenko commented Sep 16, 2022

Stumbled upon very this issue, fixed it by adjusting globPatterns — I've excluded js/html/css from it

@userquin
Copy link
Member

@victordidenko https://vite-plugin-pwa.netlify.app/guide/static-assets.html#globpatterns

@McLotos
Copy link

McLotos commented Oct 19, 2022

@ZYinMD my sw is using the const wbManifest = self.__WB_MANIFEST;, if you call registerRoute(myRoute); without calling precacheAndRoute will throw an error on runtime not in build time, just read the comments on my custom sw.

EDIT: I mean, if you're not using precacheAndRoute you cannot use registerRoute since it will check if matched on the global precache entry IIRC.

have some solution? If I don't need the precacheAndRoute (because I have to give a page asap on the first load), but need the registerRoute, now I must add console.log(self.__WB_MANIFEST) to serviceWorker, otherwise I get an error Unable to find a place to inject the manifest. This is likely because swSrc and swDest are configured to the same file. Please ensure that your swSrc file contains the following: self.__WB_MANIFEST. Adding a constant doesn't work now. console.log works, but outputs a lot of information that the user shouldn't see.

//sw.js
import { registerRoute } from 'workbox-routing'
import {
  NetworkFirst,
  StaleWhileRevalidate,
  CacheFirst
} from 'workbox-strategies'
import { CacheableResponsePlugin } from 'workbox-cacheable-response'
import { ExpirationPlugin } from 'workbox-expiration'

console.log(self.__WB_MANIFEST)

registerRoute(
  ({ request }) => request.mode === 'navigate',
  new NetworkFirst({
    cacheName: 'pages',
    plugins: [
      new CacheableResponsePlugin({
        statuses: [200]
      })
    ]
  })
)

registerRoute(
  ({ request }) =>
    request.destination === 'style' ||
    request.destination === 'script' ||
    request.destination === 'worker' ||
    request.destination === 'font',
  new StaleWhileRevalidate({
    cacheName: 'assets',
    plugins: [
      new CacheableResponsePlugin({
        statuses: [200]
      })
    ]
  })
)

registerRoute(
  ({ request }) => request.destination === 'image',
  new CacheFirst({
    cacheName: 'images',
    plugins: [
      new CacheableResponsePlugin({
        statuses: [200]
      }),
      new ExpirationPlugin({
        maxEntries: 50,
        maxAgeSeconds: 60 * 60 * 24 * 30
      })
    ]
  })
)
//vite.config.js
VitePWA({
      mode: process.env.NODE_MODE,
      base: "/",
      srcDir: "src",
      filename: "sw.js",
      includeAssets: ["/assets/favicon.png"],
      strategies: "injectManifest",
      manifest: {
        name: "CRM",
        short_name: "J-CRM",
        theme_color: "#78aab3",
        start_url: "/",
        display: "standalone",
        background_color: "#c0c0c0",
        icons: [
          {
            src: "/assets/android-chrome-192x192.png",
            sizes: "192x192",
            type: "image/png",
          },
          {
            src: "/assets/android-chrome-512x512.png",
            sizes: "512x512",
            type: "image/png",
            purpose: "any maskable",
          },
        ],
      },
    })

@userquin
Copy link
Member

@McLotos not yet, but there is a PR, check #390

@McLotos
Copy link

McLotos commented Oct 20, 2022

@McLotos not yet, but there is a PR, check #390

thnx. looking forward

@xtellur
Copy link

xtellur commented Oct 26, 2022

@McLotos not yet, but there is a PR, check #390

Awesome! Waiting for it very much, when is it going to be released?

@Hulago
Copy link

Hulago commented Feb 22, 2023

I solve my problem by using this configuration

injectManifest: {
injectionPoint: undefined
}

On VitePWA plugin.

https://vite-pwa-org.netlify.app/guide/inject-manifest.html#service-worker-code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants