GithubHelp home page GithubHelp logo

vite-pwa / vite-plugin-pwa Goto Github PK

View Code? Open in Web Editor NEW
2.8K 10.0 187.0 3.29 MB

Zero-config PWA for Vite

Home Page: https://vite-pwa-org.netlify.app/

License: MIT License

TypeScript 99.62% JavaScript 0.38%
vite-plugin vite pwa workbox vue svelte solidjs react preact

vite-plugin-pwa's Introduction

vite-plugin-pwa - Zero-config PWA for Vite
Zero-config PWA Framework-agnostic Plugin for Vite

NPM version NPM Downloads Docs & Guides
GitHub stars


๐Ÿš€ Features

  • ๐Ÿ“– Documentation & guides
  • ๐Ÿ‘Œ Zero-Config: sensible built-in default configs for common use cases
  • ๐Ÿ”ฉ Extensible: expose the full ability to customize the behavior of the plugin
  • ๐Ÿฆพ Type Strong: written in TypeScript
  • ๐Ÿ”Œ Offline Support: generate service worker with offline support (via Workbox)
  • โšก Fully tree shakable: auto inject Web App Manifest
  • ๐Ÿ’ฌ Prompt for new content: built-in support for Vanilla JavaScript, Vue 3, React, Svelte, SolidJS and Preact
  • โš™๏ธ Stale-while-revalidate: automatic reload when new content is available
  • โœจ Static assets handling: configure static assets for offline support
  • ๐Ÿž Development Support: debug your custom service worker logic as you develop your application
  • ๐Ÿ› ๏ธ Versatile: integration with meta frameworks: รฎles, SvelteKit, VitePress, Astro, Nuxt 3 and Remix
  • ๐Ÿ’ฅ PWA Assets Generator: generate all the PWA assets from a single command and a single source image
  • ๐Ÿš€ PWA Assets Integration: serving, generating and injecting PWA Assets on the fly in your application

๐Ÿ“ฆ Install

From v0.17, vite-plugin-pwa requires Vite 5.

From v0.16 vite-plugin-pwa requires Node 16 or above: workbox v7 requires Node 16 or above.

From v0.13, vite-plugin-pwa requires Vite 3.1 or above.

npm i vite-plugin-pwa -D 

# yarn 
yarn add vite-plugin-pwa -D

# pnpm 
pnpm add vite-plugin-pwa -D

๐Ÿฆ„ Usage

Add VitePWA plugin to vite.config.js / vite.config.ts and configure it:

// vite.config.js / vite.config.ts
import { VitePWA } from 'vite-plugin-pwa'

export default {
  plugins: [
    VitePWA()
  ]
}

Read the ๐Ÿ“– documentation for a complete guide on how to configure and use this plugin.

Check out the client type declarations client.d.ts for built-in frameworks support.

๐Ÿ‘€ Full config

Check out the type declaration src/types.ts and the following links for more details.

๐Ÿ“„ License

MIT License ยฉ 2020-PRESENT Anthony Fu

vite-plugin-pwa's People

Contributors

719media avatar adrianrudnik avatar allanchain avatar andipaetzold avatar antfu avatar antonofthewoods avatar arsonik avatar aryx01 avatar azamat-sharapov avatar bartek20 avatar benmccann avatar buncolak avatar cpojer avatar damianglowala avatar dargmuesli avatar davedbase avatar dimitris-toulis avatar domsen123 avatar estebanfuentealba avatar f-loat avatar filipchalupa avatar fishel-feng avatar floer32 avatar franciscohanna92 avatar hannoeru avatar holbrookdev avatar posva avatar sapphi-red avatar taigabrew avatar userquin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vite-plugin-pwa's Issues

Pictures cannot be accessed when offline

Modify based on this example
https://github.com/antfu/vite-plugin-pwa/tree/master/examples/vue-router

vite.config.js

 VitePWA({
      registerType: "autoUpdate",
      manifest: {
        version: "1.1",
        comment: "some comment",
        lang: "cn",
        name: "test",
        scope: "/",
        display: "fullscreen",
        start_url: ".",
        short_name: "test",
        description: "test66",
        orientation: "portrait",
        background_color: "#ffffff",
        theme_color: "#ffffff",
        generated: "true",
        icons: [
          {
            src: "/public/assets/images/icon.png",
            sizes: "144x144",
            type: "image/png",
          },
        ],
      },
    })

packjson.js

"dependencies": {
    "axios": "^0.21.1",
    "vue": "^3.0.11",
    "vue-router": "^4.0.6"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^1.2.1",
    "@vue/compiler-sfc": "^3.0.11",
    "animejs": "^3.2.1",
    "eslint": "^7.24.0",
    "eslint-plugin-vue": "^7.9.0",
    "sass": "^1.32.10",
    "vite": "^2.2.1",
    "vite-plugin-pwa": "^0.7.2",
    "vite-plugin-svg-icons": "^0.4.3",
    "vite-plugin-windicss": "^0.14.6",
    "windicss": "^2.5.14"
  }

In /src/pages/About

<template>
  <div>About route, built at: {{ date }} ({{ timeAgo }})</div>
  <br />
  <button @click="router.push('/')">Home</button>
  <img src="/src/img/logo.png" alt="" />
</template>

yarn start
open https://localhost Logo no problem

Refresh or re access the address after offline, and the logo will not be displayed
Want to realize all data cache, how to operate
There may be a lot of pictures in the future

Couldn't find configuration for either precaching or runtime caching.

This is my devDependencies:

  "devDependencies": {
    "@better-scroll/core": "^2.3.1",
    "@commitlint/cli": "^12.1.4",
    "@commitlint/config-angular": "^12.1.4",
    "@types/axios": "^0.14.0",
    "@types/node": "^15.6.0",
    "@vitejs/plugin-vue": "^1.2.2",
    "@vue/compiler-sfc": "^3.0.5",
    "@vueuse/core": "^4.11.0",
    "autoprefixer": "^10.2.5",
    "axios": "^0.21.1",
    "commitizen": "^4.2.3",
    "commitlint-config-cz": "^0.13.2",
    "cz-customizable": "^6.3.0",
    "eslint": "^7.27.0",
    "eslint-plugin-prettier": "^3.4.0",
    "husky": "^6.0.0",
    "lint-staged": "^10.5.3",
    "postcss": "^8.3.0",
    "prettier": "^2.2.1",
    "tailwindcss": "^2.1.2",
    "typescript": "^4.1.3",
    "vite": "^2.3.3",
    "vite-plugin-pwa": "^0.7.3",
    "vite-plugin-style-import": "^0.10.0",
    "vue-tsc": "^0.0.24",
    "xieyezi-storage": "^1.0.4"
  },

And this is my vite.config.ts:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import styleImport from 'vite-plugin-style-import';
import { resolve } from 'path'
import { VitePWA } from 'vite-plugin-pwa'


// https://vitejs.dev/config/
export default defineConfig({
  resolve: {
    alias: {
      "@src": resolve(__dirname, "./src"),
      "@assets": resolve(__dirname, "./src/assets"),
      "@components": resolve(__dirname, "./src/components"),
      "@uitl": resolve(__dirname, "./src/uitl")
    }
  },
  plugins: [
    vue(),
    styleImport({
      libs: [
        {
          libraryName: 'vant',
          esModule: true,
          resolveStyle: (name) => `vant/es/${name}/style`,
        },
      ],
    }),
    VitePWA({
      outDir: '.vue3-shopping-airi/dist',
      manifest: {
        name: 'Vue3-AiRi',
        short_name: 'AiRi',
        theme_color: '#ffffff',
        icons: [
          {
            src: '/pwa-192x192.png',
            sizes: '192x192',
            type: 'image/png',
          },
          {
            src: '/pwa-512x512.png',
            sizes: '512x512',
            type: 'image/png',
          },
        ],
      },
    }),
  ],
  server: {
    proxy: {
      '/api': {
        target: 'http://xieyezi.com:9003/mock/11/airi',
        changeOrigin: true,
        rewrite: (path: string) => path.replace(/^\/api/, '')
      }
    }
  }
})

When I run yarn build("build": "vue-tsc --noEmit && vite build"), but I get this error:

Error: Couldn't find configuration for either precaching or runtime caching. Please ensure that the various glob options are set to match one or more files, and/or configure the runtimeCaching option.

In fact ,I have cat #39 , but I dont't know how to reslove this.

So can you provide some help?

Thanks!

First build fails when the plugin is enabled for Vue 3.0

Problem:
When building a Vue 3.0 project that hasn't been built before, the plugin raises errors e.g. (the actual error depends on the configuration):

[vite-plugin-pwa] Couldn't find configuration for either precaching or runtime caching. Please ensure that the various glob options are set to match one or more files, and/or configure the runtimeCaching option.

I am not very sure if this only happens to my project because I am very new to Vue and Vite.

Environment: Windows 10

Dependencies:

    "@iconify/iconify": "^2.0.0-rc.6",
    "@vueuse/core": "^4.6.2",
    "@zxcvbn-ts/core": "^0.3.0",
    "ant-design-vue": "^2.1.2",
    "apexcharts": "^3.26.0",
    "axios": "^0.21.1",
    "crypto-js": "^4.0.0",
    "echarts": "^5.0.2",
    "lodash-es": "^4.17.21",
    "mockjs": "^1.1.0",
    "nprogress": "^0.2.0",
    "path-to-regexp": "^6.2.0",
    "print-js": "^1.6.0",
    "pwa-asset-generator": "^4.1.1",
    "qrcode": "^1.4.4",
    "sortablejs": "^1.13.0",
    "vditor": "^3.8.4",
    "vue": "3.0.7",
    "vue-echarts": "^6.0.0-rc.4",
    "vue-i18n": "^9.0.0",
    "vue-router": "^4.0.5",
    "vue-types": "^3.0.2",
    "vuex": "^4.0.0",
    "vuex-module-decorators": "^1.0.1",
    "xlsx": "^0.16.9"

Build script:

vite build && esno ./build/script/postBuild.ts

How to repeat:
Clone a project that has been successfully built before to a new machine, run yarn install to install dependencies, and run the above build command produces the errors.

Workaround
Disable the plugin (unimporting it) temporarily from the app and run the first build. After that, the plugin causes no trouble anymore in building.

How disable `injectManifest` ?

I Try use this plugin in Electron app.

Technically, this is a web page with a strict Content-Security-Policy.
During development, the page runs at http://localhost:3000, and in the production environment as file:///C:/path-to/app/resources/index.html

Precache, I think, is not very important for my, because all assets are located locally anyway. But using the schema file: imposes certain problems for the service worker.

Therefore, I am only interested in the service worker as a tool for caching network requests. And I want to completely disable injectManifest.

I tryed

    VitePWA({
      injectRegister:'script',
      manifest: false,
      injectManifest: false,
})

But in sw.js still has

  workbox.precacheAndRoute([{
    "url": "index.8daf1fe7.css",
    "revision": "bb76d49a4d80950ac285a814832c9c8a"
  }, {
    "url": "index.f66a5a19.js",
    "revision": "a8e69220ac0a4822a5e98ec359765139"
  }, {
    "url": "index.html",
    "revision": "7c2b1f2f6f2698a7dd5ba69c1e4ca1c3"
  }, {
    "url": "registerSW.js",
    "revision": "e21bbf02f2e95e944e8acae5f65ca7f7"
  }, {
    "url": "vendor.f57ce527.js",
    "revision": "cbcca323ae9391f4ef2f13c0065e7abd"
  }, {
    "url": "Watch.8c7a9f24.js",
    "revision": "b7aceb22f06e7a44553c43001c7c1f60"
  }], {});

cleanup: docs and `injectManifest` build

This is a hint for clenaup, I'll do a PR in a few minutes:

  • remove WIP: Icons generation for different dimensions from README.md file: it will not be included, since there is a lot of tools out there.
  • remove import dynamic polyfill when generating injectManifest from plugins list: dynamic import polyfill is removed in the latest vite, we could safely ignore it.

@antfu there is no need to generate a new release for those changes once the new PR merged: since injectManifest is just filtering the plugins used to build the custom service worker using the name of the plugin, if using new vite version will not have this plugin, and so it will not be used.

ValidationError: "importWorkboxFrom" is not allowed

Hey there, I get this error message when building:

$ npx vite build
vite v2.0.2 building for production...
โœ“ 1036 modules transformed.
(node:21472) UnhandledPromiseRejectionWarning: ValidationError: "importWorkboxFrom" is not allowed
(node:21472) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:21472) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

The build itself seems to work, but I'm not sure what the error message means.

This is my vite.config.js:

module.exports = {
	plugins: [
		VitePWA({
			strategies: 'injectManifest',
			injectManifest: {
				importWorkboxFrom: 'local',
				swSrc: './src/ServiceWorker/sw.js',
			},
			manifest: {
				// ... A lot of manifest config ...
			},
		}),
	],
}

Question: Nested paths breaks lighthouse PWA test

I have found some problems when using nested routes with the plugin: lighthouse cannot resolve start_url when in nested path route, for example just request https://vitesse.netlify.app/hi/a in private mode on chrome, open dev tools and run lighthouse with PWA check checked:

imagen

The problem in question can be solved just adding the scope to the manifest.webmanifest file and also initializing it with the basePath.

By default it is initialized as ./, and I don't know if this value is ok to be used as scope when registering the service worker. I register it using router.isReady callback instead on index page and change the default pattern to be /, and so the header, the manifest.webmanifest and the registration matches:

imagen

This is because it seems that the nested parent path acts as a new scope, that is distinct from the missing scope.

Another think that I don't know if it is required is to add a header like that to the html (I just add it as a http header from the server side):

service-worker-allowed: `${basePath}`

Here is a working manifest.webmanifest.

You can see a working sample here: https://cancer.malvarez.info/conozca-su-riesgo, then click on + icon and run the test (it is with vite 1 + vitesse 1, I'm migrating it to vite 2 + vitesse 2).

run "vite" get a error "Error: The following dependencies are imported but could not be resolved:"

ENV

  • node
    v15.14.0
  • npm
    7.10.0
  • "vite": "^2.0.1",
  • "vite-plugin-pwa": "^0.7.2",

devDependencies

  "devDependencies": {
    "@commitlint/cli": "^12.1.1",
    "@commitlint/config-conventional": "^12.1.1",
    "@types/node": "^15.0.1",
    "@typescript-eslint/eslint-plugin": "^4.22.0",
    "@typescript-eslint/parser": "^4.22.0",
    "@vitejs/plugin-vue": "^1.1.4",
    "@vue/compiler-sfc": "^3.0.5",
    "commitizen": "^4.2.3",
    "cz-conventional-changelog": "^3.2.0",
    "cz-customizable": "^6.3.0",
    "eslint": "^7.25.0",
    "eslint-config-airbnb-base": "^14.2.1",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-prettier": "^3.4.0",
    "eslint-plugin-vue": "^7.9.0",
    "https-localhost": "^4.6.4",
    "husky": "^6.0.0",
    "lint-staged": "^10.5.4",
    "prettier": "^2.2.1",
    "stylus": "^0.54.8",
    "typescript": "^4.1.3",
    "vite": "^2.0.1",
    "vite-plugin-pwa": "^0.7.2",
    "vite-plugin-style-import": "^0.9.2"
  },

full error message

error when starting dev server:
Error: The following dependencies are imported but could not be resolved:

  virtual:pwa-register (imported by /Users/baboon/github/picx/src/common/utils/registerSW.ts)

Are they installed?
    at optimizeDeps (/Users/baboon/github/picx/node_modules/vite/dist/node/chunks/dep-e9a16784.js:64742:15)
    at processTicksAndRejections (node:internal/process/task_queues:94:5)
    at async runOptimize (/Users/baboon/github/picx/node_modules/vite/dist/node/chunks/dep-e9a16784.js:68555:48)
    at async Server.httpServer.listen (/Users/baboon/github/picx/node_modules/vite/dist/node/chunks/dep-e9a16784.js:68569:17)

After packaging, registersw.js is not automatically introduced into index.html

"vite": "^2.3.5"

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import viteCompression from "vite-plugin-compression";
import { VitePWA } from "vite-plugin-pwa";

// https://vitejs.dev/config/
export default defineConfig({
  build: {
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true,
      },
    },
  },
  plugins: [
    viteCompression({
      verbose: true,
      algorithm: "gzip",
      threshold: 10240
    }),
    VitePWA({
      manifest: {
        name: "็ง‘ๆŠ€",
        short_name: "็ง‘ๆŠ€",
        display: "standalone",
        icons: [
          { src: "/logo*512.png", type: "image/png", sizes: "512x512" },
          { src: "/logo*256.png", type: "image/png", sizes: "256x256" },
          { src: "/logo*128.png", type: "image/png", sizes: "128x128" },
          { src: "/logo*64.png", type: "image/png", sizes: "64x64" },
        ],
        start_url: "/",
        background_color: "#F9F9F9",
        theme_color: "#3A3F51",
      },
      workbox: {
        skipWaiting: true,
        clientsClaim: true,
      },
    }),
    vue(),
  ],
});

After packaging...

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite App</title>
  <script type="module" crossorigin src="/assets/index.d57a7ae8.js"></script>
  <link rel="modulepreload" href="/assets/vendor.170a6766.js">
  <link rel="stylesheet" href="/assets/index.ca835772.css">
<link rel="manifest" href="/manifest.webmanifest"></head>
  <body>
    <div id="app"></div>
    
  </body>
</html>

Question about preloading excluded assets

I have a small app using vitesse template (that uses this plugin) and I have a problem with some SVG images that are not included on assets directory (are too big to be inlined, and then vite just set its href to undefined, so I moved them to public directory), but then, this plugin excludes these images from PWA, or at least once installed (PWA on client), these SVG are not downloaded (and when testing offline, just alt attribute are displayed instead SVG).

I'm looking to use prefetching these SVG once the page is requested, but the problem pages are served from external server (webflux kotlin server with freemarker template) and the rest of pages are excluded (I have 4 pages, one containing a subgroup of these SVG and another containing other subgroup of these SVG). Maybe preloading all pages via html link will work (I've not test yet)?

I use server push on server side once each page is requested using vite manifest.json file, so when requesting a page all resources are just cached.

Is there a way to include some prefetch via these plugin to hook into the workbox or I just need to use Cache Storage API?

Another question is about user feedback:
How to integrate with these plugin?

Any suggestions are welcome.

Thx in advance.

Make dist folder configurable

You have static dist/sw.js and dist/manifest.webmanifest and cannot be changed.

It fails if I use outDir: 'web-resources' on vite.config.ts file.

docs inconsistency

Hi, I am not sure which one is correct.

In examples useRegisterSW is used

import { useRegisterSW } from "virtual:pwa-register/vue"

and in docs we see registerSW

import { registerSW } from "virtual:pwa-register/vue"

Which one is correct?

Thanks

Allow manually registering

By default, the following script is added to the index.html

<script>if('serviceWorker' in navigator) {window.addEventListener('load', () => {navigator.serviceWorker.register('/service-worker.js', { scope: '/' })})}</script>

If I specify inlineRegister: false, I'll get

<script src="/registerSW.js"></script>

I don't see a way how I can control the registration of the service worker myself.

Please add an option to leave out the registration code.

Is it possible somehow register a serviceWorker in `development`?

I understand that in most cases it's superfluous but I have a slightly non-standard case)

My application is mostly placed on the third party's api. This API works slowly, and has a limit for requests. On development (when you often load and reload page many times), the page I create a lot of requests to this api, it slows down my work and exhausts all the limits.

I see a service worker as a good solution to this problem.
In production are all great. Network requests to the third party API use the CacheFirst strategy. This is accelerating the work of the application and reduces the load on the remote server.

I have no need to take over about actual of data and I would like to apply the same caching strategy for development too.

getting started doc

Hi,
i'm newer to pwa, is there any doc/example for getting started? is there "registerServiceWorker.js" like vue cli? where to put the "maniestfest" file? Thanks a lot for your great help.

false-positive error masks real error (vercel deployment)

Hello,

I have seen an error that pops only when I deploy to vercel.

If there is some error in my code, and I push to vercel, the build process will give me the following error 100% of the time:
Error: Couldn't find configuration for either precaching or runtime caching. Please ensure that the various glob options are set to match one or more files, and/or configure the runtimeCaching option.

The problem is that I have to remove the VitePWA config from vite.config.js, and push again, in order to have the real error showing up :
Error: Preprocessor dependency "sass" not found. Did you install it?

I know then, that I have to add sass as a dependency (Already was globally installed on my local environnement, so it didn't trigger on local build).

When i resolve the error (sass dependency), and add back VitePWA config, everything works fine.

/* package.json */
{
  "name": "xxx",
  "version": "0.0.0",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "serve": "vite preview",
    "analysis": "windicss-analysis"
  },
  "dependencies": {
    "axios": "^0.21.1",
    "dayjs": "^1.10.4",
    "mangopay-cardregistration-js-kit": "^1.2.2",
    "vee-validate": "^4.4.0",
    "vue": "^3.0.5",
    "vue-router": "^4.0.6",
    "vue3-carousel": "^0.1.15",
    "vue3-click-away": "^1.2.1",
    "vuex": "^4.0.0",
    "yup": "^0.32.9"
  },
  "devDependencies": {
    "@iconify/json": "^1.1.327",
    "@vitejs/plugin-vue": "^1.2.1",
    "@vue/compiler-sfc": "^3.0.5",
    "node-sass": "^5.0.0",
    "sass": "^1.34.0",
    "sass-loader": "^11.1.0",
    "vite": "^2.1.5",
    "vite-plugin-components": "^0.8.3",
    "vite-plugin-icons": "^0.4.0",
    "vite-plugin-pwa": "^0.7.3",
    "vite-plugin-windicss": "0.12.5",
    "windicss-analysis": "^0.2.0"
  }
}
/* vite.config.js */
import { defineConfig } from 'vite'
import path from 'path'
import vue from '@vitejs/plugin-vue'
import WindiCSS from 'vite-plugin-windicss'
import ViteComponents from 'vite-plugin-components'
import ViteIcons, { ViteIconsResolver } from 'vite-plugin-icons'
import { VitePWA } from 'vite-plugin-pwa'

// https://vitejs.dev/config/
export default defineConfig({
  resolve: {
    alias: {
      '@/': `${path.resolve(__dirname, 'src')}/`,
    },
  },
  plugins: [
    vue(),
    WindiCSS(),
    ViteComponents({
      extensions: ['vue'],

      // auto import icons
      customComponentResolvers: [
        ViteIconsResolver({
          componentPrefix: '',
          // enabledCollections: ['carbon']
        }),
      ],
    }),
    ViteIcons(),
    // https://github.com/antfu/vite-plugin-pwa
    VitePWA({
      registerType: 'autoUpdate',
      manifest: {
        name: 'xxxx',
        short_name: 'xxxx',
        theme_color: '#ffffff',
        icons: [
          {
            src: '/pwa-192x192.png',
            sizes: '192x192',
            type: 'image/png',
          },
          {
            src: '/pwa-512x512.png',
            sizes: '512x512',
            type: 'image/png',
          },
          {
            src: '/pwa-512x512.png',
            sizes: '512x512',
            type: 'image/png',
            purpose: 'any maskable',
          },
        ],
      },
    }),
  ]
})

Plugin doesn't work on React vite template?

import { registerSW } from 'virtual:pwa-register'
 
registerSW({
  onOfflineReady() {
    // show a ready to work offline to user
  },
})

Upon build

$ tsc && vite build
node_modules/vite-plugin-pwa/client.d.ts:12:28 - error TS2307: Cannot find module 'vue' or its corresponding type declarations.

import type { Ref } from 'vue'

Do I have to install vue for this plugin to work?

EDIT:

I had to include node_modules/vite-plugin-pwa/client.d.ts in tsconfig.json for VScode to even pick up that such a module exists.

Create a svelte-kit example

I know svelte-kit is in beta, but this vite-plugin-pwa seems a good fit with svelte-kit.
I gave it a try but so far am not succeeding. The npm run build seems to perform correctly but the generated code makes use of navigator and the result fails. It could be due to the SSR that svelte-kit does.

updateServiceWorker does nothing

I'm using injectManifest mode and this is my config

VitePWA({
    strategies: 'injectManifest',
    manifest,
    srcDir: './src/service-worker',
    filename: 'index.js',
    outDir: './dist',
    injectRegister: 'auto'
}),

And later on to implement the ReloadPrompt component,

<button v-if="newVersionAvailable" @click="updateServiceWorker">
    Update to the latest version
</button>
const {
    needRefresh
    updateServiceWorker
} = useRegisterSW();

But updateServiceWorker practically does nothing.
It just returns a promise that resolves to nothing.
I looked into the source code and saw if (!auto) { in updateServiceWorker function.
Then saw this const autoUpdateMode = '__SW_AUTO_UPDATE__' which updateServiceWorker is depend on. Then, found out that __SW_AUTO_UPDATE__ is getting replaced by ${options.registerType === 'autoUpdate'}. But I don't want an autoUpdate when I'm using a reload prompt. I lost.

Minified output

Service worker and Workbox javascript files are not minified. Is there any option I should add or is it missing this feature?

Don't auto-create webmanifest

Hi!

Is it possible to NOT auto-create and inject the manifest.webmanifest but only generate the service worker?

My manifest needs to be loaded from a different server.

Thanks.

Automatically add manifest icons to build dir

Hi, I don't know if it's a bug or a feature request but it would be fantastic if the images listed in the icons[] array of the manifest would be automatically added to the build dir (dist/assets by default).

Cannot find module 'virtual:pwa-register' in vscode

Hi, vscode is showing error ts2307 on the line import { registerSW } from 'virtual:pwa-register' which is near the top of my app.ts file. Everything compiles and works, but vscode is complaining. I'm wondering whether it's a problem or something I missed?

Resolve imports when bundling

As per the workbox docs, I have this in my service worker file:

import { precacheAndRoute } from 'workbox-precaching'
precacheAndRoute(self.__WB_MANIFEST)

However, when I build my app, that part stays the same which results in the service worker not working because browsers can't execute js import statements in service workers (at least for now). It fails to execute the service worker with the error Uncaught SyntaxError: Cannot use import statement outside a module.

Not sure if this is an issue with the bundler or my understanding of workbox. All examples use import statements.

Relevant part of my vite.config.js:

VitePWA({
	strategies: 'injectManifest',
	injectRegister: false, // service worker is registered from a separate script.
	injectManifest: {
		swSrc: './src/ServiceWorker/sw.js',
		swDest: './dist/sw.js',
	},
	manifest: {
		// manifest omitted
	}
}),

[Question] sw.js injected inline

Hi,
im running VitePWA with ViteSSG.
The build process is injecting the sw.js into index.html as inline script..

Can I move this into a separate file?
Don't want to inject this as inline script cause of my Content Security Policy.

Bug: Netlify redirects do not work anymore

Description
I've a simple Vite project at https://github.com/liyasthomas/liyasthomas.com hosted on Netlify with some redirects on sub pages. I installed vite-plugin-pwa and now its redirects are not working anymore. PWA plugin's readme doesn't have anything regarding how installing vite-plugin-pwa affects routing.

Steps to reproduce

  1. Spin up a Vite + Vue 3 project

  2. Host on netlify with a redirect on Netlify:

    netlify.toml

       [[redirects]]
         from = "/abc"
         to = "https://abc.com"
         status = 301
         force = true
    
  3. Install vite-plugin-pwa

  4. Redirects are broken

include custom files/dirs in sw cache?

Hello,
I have a directory /public/images which contain icons. the icons are referenced in index.html and the pwa webmanifest as /images/icon-x.png.
The images directory is moved to the dist folder on build, as expect. but it is not included in the cache, which is kinda expected as well.
Can I include it manually? The images disappear right after reload when the app goes offline.

Note: I've tried using the assetsInclude config of Vite, as the PWA manifest config don't automatically change URLs to generated ones, meaning in webmanifest /images/icon-x.png don't turn into /images/icon-x-123ea.png` on build.

demo link if needed: https://vite-alpine-pwa.vercel.app/

Bust cache after a release?

Hello, I'm not well versed in PWA settings, and your plugin works really well as a 0-config tool (thanks for that).

However, I'm faced with a cache issue when I'm redeploying my app. In that case, I had to rename several api endpoints on my backend, but once the Vue app was built and deployed, all I got was 404 errors because I was still served the app from the cache. Since it's still in dev I simply manually unregistered the worker, but I what to do if that happens in production?

If I understand correctly, even if all my .js files and assets have a versioned hash in their name, as long as the index.html file is cached, it will still serve the old assets.

Is there a configuration I can setup (maybe it's still WIP on your side) to fix this, or if applicable, is there something you recommend? I found several solutions for this issue, but nothing looks really clean or fail-proof.

"The start_url did respond, but not via a service worker"

Hello,

I installed your plugin over a VueJS 3 / Vite 2 app, configured it as best as I can, and Lighthouse returns this error:
image

How can I fix this issue?

My vite.config.ts:

const config: UserConfig = {
  plugins: [
    vue(),
    VitePWA({
      manifest: {
        icons: [
          {
            src: 'img/icons/graph-144.png',
            sizes: '144x144',
            type: 'image/png',
            purpose: 'maskable'
          }
        ],
        theme_color: '#34b4e4'
      }
    })
  ],
  alias: {
    '@': resolve(__dirname, 'src')
  }
}

Aws build error

Hi,

Prevented us from tracking other errors in AWS code builds
How do I fix it?

image

random behaviour

Sometimes the plugin doesn't add the list of precached files to service-worker properly; getting an empty array insted.

I running many builds to test the plugin with alternate between modes (injectManifest and generateSW) and configurations and getting the same inconcistent results.

Finally, I download the repo and build a custom variant of the plugin changing the hook used for use workbox-build (closeBundle insted of buildEnd) and now all builds output the right precached files always.

// index.ts
closeBundle() { // line changed
      if (options.strategies === 'injectManifest')
        injectManifest(options.injectManifest)
      else \
        generateSW(options.workbox)
    },

This change could be add to the plugin? or is a wrong solution?

I could do a pull request. :)

Browser is not detecting Service Worker

I have configured the manifest option as per the docs but still, the service worker is not detected by the browser.

My Dependencies

"dependencies": {
    "vue": "^3.0.5",
    "vue-router": "^4.0.6",
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^1.2.1",
    "@vue/compiler-sfc": "^3.0.5",
    "autoprefixer": "^10.2.5",
    "postcss": "^8.2.10",
    "tailwindcss": "^2.1.1",
    "vite": "^2.1.5",
    "vite-plugin-pwa": "^0.7.0"
  }

Here is my repo https://github.com/jahidanowar/qrcodescanner

Support "base" path from vite config

Hey,

When building static assets from VitePWA, the paths to the service worker and the manifest is hardcoded (at root level)
Would it be possible to preprend them with the "base" config from vite?

Provide types for the client functions

Provide some typings for the virtual:pwa-register/vue & virtual:pwa-register imports

example:

declare module "virtual:pwa-register/vue" {
  import { Ref } from "vue";
  type RegisterSWOptions = {
    immediate?: boolean;
    onNeedRefresh?: () => void;
    onOfflineReady?: () => void;
  };

  function useRegisterSW(
    options?: RegisterSWOptions
  ): {
    needRefresh: Ref<boolean>;
    offlineReady: Ref<boolean>;
    updateServiceWorker(reloadPage?: boolean): void;
  };
}
declare module "virtual:pwa-register" {
  type RegisterSWOptions = {
    immediate?: boolean;
    onNeedRefresh?: () => void;
    onOfflineReady?: () => void;
  };

  function registerSW(
    options?: RegisterSWOptions
  ): (reloadPage?: boolean) => void;
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.