Coder Social home page Coder Social logo

pwa's Introduction

Qwik PWA 📱

Turn your Qwik Application into an offline compatible PWA (Progressive Web Application) using Workbox but without the hassle.

Installation

npm install --save-dev @qwikdev/pwa

vite.config.ts:

import { qwikPwa } from "@qwikdev/pwa";

export default defineConfig(() => {
  return {
    define: {
      // (optional) enables debugging in workbox
      "process.env.NODE_ENV": JSON.stringify("development"),
    },
    plugins: [
      qwikCity(),
      qwikVite(),
      // The options are set by default
      qwikPwa({
        /* options */
      }),
    ],
  };
});

src/routes/service-worker.ts:

import { setupServiceWorker } from "@builder.io/qwik-city/service-worker";
import { setupPwa } from "@qwikdev/pwa/sw";

setupServiceWorker();

+setupPwa();

- addEventListener("install", () => self.skipWaiting());

- addEventListener("activate", () => self.clients.claim());

- declare const self: ServiceWorkerGlobalScope;

By default, your application will be auto-updated when there's a new version of the service worker available and it is installed: in a future version, you will be able to customize this behavior to use prompt for update:

import { setupServiceWorker } from "@builder.io/qwik-city/service-worker";
import { setupPwa } from "@qwikdev/pwa/sw";

setupServiceWorker();
setupPwa("prompt");

public/manifest.json:

"background_color": "#fff",
+ "theme_color": "#fff",

For more information, check the following pages:

src/components/router-head/router-head.tsx:

// PWA compatible generated icons for different browsers
import * as pwaHead from "@qwikdev/pwa/head";

export const RouterHead = component$(() => {
    ...
      {pwaHead.meta.map((l) => (
        <meta key={l.key} {...l} />
      ))}
      {pwaHead.links.map((l) => (
        <link key={l.key} {...l} />
      ))}
    ...

Make sure you remove the <link rel="icon" type="image/svg+xml" href="/favicon.svg" /> line in your router-head file.

Now your application is PWA-friendly.

Precache

One feature of service workers is the ability to save a set of files to the cache when the service worker is installing. This is often referred to as "precaching", since you are caching content ahead of the service worker being used. Chrome for Developers

Assets

Assets like js modules generated by qwik (q-*.js), images, public/ assets, or any file that's emitted in the dist/ directory by the build step would be precached when the service worker instantiates, so the plugin makes sure it provides the best client-side offline experience.

Routes

By default in this plugin, every route that does not include params (/ or /demo/flower) is precached on the first run of the application when the browser registers the service worker.

For the rest of the defined routes (routes with params like /dynamic/[id], SSG routes, or API routes), they are not precached, but there are workbox navigation routes defined that would cache them on-demand and per request, the reason is precaching too many assets on the first run would cause a laggy experience for the user, especially when these kind of routes have the potential to generate so many more files.

Imagine there's an SSG /blog/[id] route that generates 120 blog posts, in this case, fetching 120 pages of blog posts in the application startup would not seem ideal.

Solution

Just fetch the desired page or asset so it gets cached for later uses.

fetch("/blog/how-to-use-qwik");

API Routes

For API routes and any other routes that do not meet the conditions mentioned above, there's a Network-First handler.

Manifest

The plugin would generate all of the adaptive icons needed for different devices with different ratios in manifest.json based on your main icon in the build process using @vite-pwa/assets-generator.

Screenshots

For full PWA compatibility, you can put your screenshots with the following pattern in the public/manifest.json file.

    ...
    "screenshots": [
        {
            "src": "/screenshot.png",
            "type": "image/png",
            "sizes": "862x568"
        },
        {
            "src": "/screenshot.png",
            "type": "image/png",
            "sizes": "862x568",
            "form_factor": "wide"
        }
    ]

For beautiful screenshots, you can use Progressier Screenshots Generator.

Cloudflare deployment

PNPM

  1. Need set resolutions w/ "sharp": "0.32.6" on package.json;
  2. It is necessary to create a file npm-lock.yaml by pnpm install.

Bun

  1. Need set resolutions w/ "sharp": "0.32.6" on package.json;
  2. It is necessary to create a file bun.lockb by bun install.
  3. Set ENV BUN_VERSION=1.0.5 (or higher) in Cloudflare. Cuz the default version of Bun - 1.0.1 doesn't work.

pwa's People

Contributors

aslemammad avatar userquin avatar amirsa12 avatar dejurin avatar

Stargazers

Christos Poulias avatar Daniel Bayley avatar Ahmed Chakhoum avatar Raul Rodriguez avatar Saeed Nemati avatar  avatar Evander Otieno avatar Tom Stejskal avatar Rasmus Madsen avatar Thomas Peißl avatar Linden Quan avatar Miguel GP avatar Jauhar Muhammed avatar Matthew Lal avatar Isaac Garcia avatar Moi avatar Seth Horsley avatar  avatar Vladislav Lipatov avatar Abraham Schilling avatar Tom Schönmann avatar Pridsadang Pansiri avatar Avaray avatar  avatar Teerapat Prommarak avatar Adrien Peyre avatar Adnan Ebrahimi avatar  avatar Turan Rustamli avatar Jhonathan Izquierdo Higuita avatar AmirHossain Zohrabi avatar Mohammad RAHMANI avatar Chris Yang avatar Abdullah Mzaien avatar Njogu Amos avatar Guillaume Humbert avatar Robert Hurst avatar Hyeseong Kim avatar  avatar Ariel Vieira avatar  avatar Ian Jamieson avatar Sebastian Duque Gutierrez avatar Jordan Arentsen avatar  avatar Antônio Abrantes avatar Jack Shelton avatar ⊣˚∆˚⊢ avatar its-frank-huang avatar Agustinus Nathaniel avatar Muhammad Farid Zia avatar  avatar Ryo Sogawa avatar Hatem Hosny avatar CA Gustavo avatar  avatar Vince Speelman avatar Brandon Pittman avatar  avatar Udula Akash avatar Nick K. avatar PatrickJS avatar J. Fitzgerald Flood avatar Tobias Wittwer avatar Adir Amsalem avatar Shai Reznik avatar Quentin Delettre avatar Timothy Michael McMasters avatar Yoav Ganbar avatar  avatar Stefano Magni avatar Kermout Ayoub avatar Zafar Ansari avatar loclv avatar Muhammad avatar Corey Jepperson avatar Abner Luis Rodrigues avatar Aurélien Lourot avatar Thiha avatar Alireza Aghaee avatar Sajjad Soudani avatar Maïeul avatar  avatar Enes Kavçakar avatar Kyle Bario avatar

Watchers

MohsinAli avatar  avatar  avatar

pwa's Issues

Cloudflare build fail

Hello, there
I got problem again.

I copy your example and change it only:

- "@qwikdev/pwa": "workspace:../",
+ "@qwikdev/pwa": "^0.0.4",

Repo: https://github.com/dejurin/pwa-example/blob/main/package.json

I tried pnpm and npm ...
I tried remove pnpm-lock.yaml file, and update all deps, nothing works...
Please, try to build for Cloudflare.

Build log fail

2024-02-29T10:46:14.675867851Z	Cloning repository...
2024-02-29T10:46:15.817757913Z	From https://github.com/dejurin/pwa-example
2024-02-29T10:46:15.818414405Z	 * branch            13c07dbc1f5f9e9e5e134c65a5fad4f03572787e -> FETCH_HEAD
2024-02-29T10:46:15.818434068Z	
2024-02-29T10:46:15.880212665Z	HEAD is now at 13c07db Update .node-version
2024-02-29T10:46:15.880493728Z	
2024-02-29T10:46:15.986002553Z	
2024-02-29T10:46:15.986690601Z	Using v2 root directory strategy
2024-02-29T10:46:16.017917111Z	Success: Finished cloning repository files
2024-02-29T10:46:16.746843789Z	Detected the following tools from environment: [email protected], [email protected]
2024-02-29T10:46:17.72034778Z	Installing project dependencies: pnpm install
2024-02-29T10:46:18.536833368Z	Lockfile is up to date, resolution step is skipped
2024-02-29T10:46:18.573150688Z	Progress: resolved 1, reused 0, downloaded 0, added 0
2024-02-29T10:46:18.676341818Z	Packages: +473
2024-02-29T10:46:18.676655414Z	++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2024-02-29T10:46:19.602499285Z	Progress: resolved 473, reused 0, downloaded 34, added 29
2024-02-29T10:46:20.609502575Z	Progress: resolved 473, reused 0, downloaded 231, added 226
2024-02-29T10:46:21.601956827Z	Progress: resolved 473, reused 0, downloaded 397, added 390
2024-02-29T10:46:22.60315293Z	Progress: resolved 473, reused 0, downloaded 472, added 472
2024-02-29T10:46:23.308801677Z	Progress: resolved 473, reused 0, downloaded 473, added 473, done
2024-02-29T10:46:23.579538619Z	.../[email protected]/node_modules/sharp install$ (node install/libvips && node install/dll-copy && prebuild-install) || (node install/can-compile && node-gyp rebuild && node install/dll-copy)
2024-02-29T10:46:23.839255698Z	.../[email protected]/node_modules/sharp install: sharp: Downloading https://github.com/lovell/sharp-libvips/releases/download/v8.14.5/libvips-8.14.5-linux-x64.tar.br
2024-02-29T10:46:24.581973176Z	.../[email protected]/node_modules/sharp install: sharp: Integrity check passed for linux-x64
2024-02-29T10:46:25.238851449Z	.../[email protected]/node_modules/sharp install: Done
2024-02-29T10:46:25.331737597Z	.../[email protected]/node_modules/esbuild postinstall$ node install.js
2024-02-29T10:46:25.33222948Z	.../[email protected]/node_modules/esbuild postinstall$ node install.js
2024-02-29T10:46:25.332693538Z	.../[email protected]/node_modules/esbuild postinstall$ node install.js
2024-02-29T10:46:25.413664247Z	.../node_modules/workerd postinstall$ node install.js
2024-02-29T10:46:25.454400927Z	.../[email protected]/node_modules/esbuild postinstall: Done
2024-02-29T10:46:25.498908901Z	.../[email protected]/node_modules/esbuild postinstall: Done
2024-02-29T10:46:25.525594378Z	.../[email protected]/node_modules/esbuild postinstall: Done
2024-02-29T10:46:25.56326139Z	.../node_modules/workerd postinstall: Done
2024-02-29T10:46:26.196556951Z	.../[email protected]/node_modules/sharp install$ node install/check
2024-02-29T10:46:26.346857447Z	.../[email protected]/node_modules/sharp install: Done
2024-02-29T10:46:26.476881955Z	
2024-02-29T10:46:26.477224116Z	devDependencies:
2024-02-29T10:46:26.477454961Z	+ @builder.io/qwik 1.4.5
2024-02-29T10:46:26.477682651Z	+ @builder.io/qwik-city 1.4.5
2024-02-29T10:46:26.477971167Z	+ @qwikdev/pwa 0.0.4
2024-02-29T10:46:26.478838721Z	+ @types/eslint 8.56.5
2024-02-29T10:46:26.478857865Z	+ @types/node 20.11.22
2024-02-29T10:46:26.47886393Z	+ @typescript-eslint/eslint-plugin 6.21.0
2024-02-29T10:46:26.478868273Z	+ @typescript-eslint/parser 6.21.0
2024-02-29T10:46:26.478872451Z	+ @vite-pwa/assets-generator 0.2.4
2024-02-29T10:46:26.479262839Z	+ eslint 8.57.0
2024-02-29T10:46:26.480167313Z	+ eslint-plugin-qwik 1.4.5
2024-02-29T10:46:26.480334579Z	+ fast-glob 3.3.2
2024-02-29T10:46:26.480530861Z	+ prettier 3.2.5
2024-02-29T10:46:26.480774532Z	+ typescript 5.3.3
2024-02-29T10:46:26.480968536Z	+ undici 5.28.3
2024-02-29T10:46:26.481021372Z	+ vite 4.5.2
2024-02-29T10:46:26.481231396Z	+ vite-tsconfig-paths 4.3.1
2024-02-29T10:46:26.481297613Z	+ wrangler 3.30.0
2024-02-29T10:46:26.481662611Z	
2024-02-29T10:46:26.494238144Z	Done in 8.3s
2024-02-29T10:46:26.602171663Z	Executing user command: pnpm run build
2024-02-29T10:46:27.385057161Z	
2024-02-29T10:46:27.385873656Z	> example@ build /opt/buildhome/repo
2024-02-29T10:46:27.385894019Z	> qwik build
2024-02-29T10:46:27.385899146Z	
2024-02-29T10:46:27.495460046Z	
2024-02-29T10:46:27.496064425Z	      ............
2024-02-29T10:46:27.496287304Z	    .::: :--------:.
2024-02-29T10:46:27.49638399Z	   .::::  .:-------:.
2024-02-29T10:46:27.496498048Z	  .:::::.   .:-------.
2024-02-29T10:46:27.496606525Z	  ::::::.     .:------.
2024-02-29T10:46:27.496762169Z	 ::::::.        :-----:
2024-02-29T10:46:27.496786764Z	 ::::::.       .:-----.
2024-02-29T10:46:27.496978818Z	  :::::::.     .-----.
2024-02-29T10:46:27.497688077Z	   ::::::::..   ---:.
2024-02-29T10:46:27.497725197Z	    .:::::::::. :-:.
2024-02-29T10:46:27.497730263Z	     ..::::::::::::
2024-02-29T10:46:27.497734637Z	             ...::::
2024-02-29T10:46:27.497737756Z	     
2024-02-29T10:46:27.497740857Z	
2024-02-29T10:46:27.497748091Z	
2024-02-29T10:46:27.497836678Z	pnpm run build.client
2024-02-29T10:46:27.497882307Z	pnpm run build.server
2024-02-29T10:46:27.498059415Z	
2024-02-29T10:46:28.013439697Z	
2024-02-29T10:46:28.013693717Z	> example@ build.client /opt/buildhome/repo
2024-02-29T10:46:28.013883179Z	> vite build
2024-02-29T10:46:28.014059053Z	
2024-02-29T10:46:28.395457804Z	�[33mThe CJS build of Vite's Node API is deprecated. See https://vitejs.dev/guide/troubleshooting.html#vite-cjs-node-api-deprecated for more details.�[39m
2024-02-29T10:46:29.229356148Z	�[36mvite v4.5.2 �[32mbuilding for production...�[36m�[39m
2024-02-29T10:46:29.374991534Z	transforming...
2024-02-29T10:46:29.566201966Z	munmap_chunk(): invalid pointer
2024-02-29T10:46:29.582554916Z	Aborted
2024-02-29T10:46:29.588858366Z	 ELIFECYCLE  Command failed with exit code 134.
2024-02-29T10:46:29.639025963Z	 ELIFECYCLE  Command failed with exit code 1.
2024-02-29T10:46:29.668404129Z	Failed: Error while executing user command. Exited with error code: 1
2024-02-29T10:46:29.680114675Z	Failed: build command exited with code: 1
2024-02-29T10:46:30.646625Z	Failed: error occurred while running build command

Can't build using Vercel adapter

i use @qwikdev/pwa & the vercel adapter (for building)
+the default setup in pwa/README.md

pnpm run build does
(process:12632): GLib-GObject-CRITICAL **: 21:35:04.401: invalid unclassed type '(NULL)' in class cast to '(NULL)' as warning
and exit with :

error during build:
Error: ENOENT: no such file or directory, open '{rep_path}\dist\service-worker.js'
    at async open (node:internal/fs/promises:633:25)
    at async Object.readFile (node:internal/fs/promises:1242:14)
    at async Object.handler (file:///{rep_path}/node_modules/.pnpm/@[email protected]/node_modules/@qwikdev/pwa/lib/index.qwik.js:118:24)
    at async PluginDriver.hookParallel (file:///{rep_path}/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/node-entry.js:19485:17)
    at async Object.close (file:///{rep_path}/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/node-entry.js:20418:13)
    at async build (file:///{rep_path}/node_modules/.pnpm/[email protected]_@[email protected]/node_modules/vite/dist/node/chunks/dep-BBHrJRja.js:67290:13)
    at async CAC.<anonymous> (file:///{rep_path}/node_modules/.pnpm/[email protected]_@[email protected]/node_modules/vite/dist/node/cli.js:842:9)
 ELIFECYCLE  Command failed with exit code 1.

the issue is that there is no dist folder in the basepath (no /dist) but in /.vercel/output/static
i already spotted the variable that point to the wrong path in src/context.ts:67 (from pwa rep)

  // [...]
  ctx.clientOutDir = ctx.qwikPlugin!.api.getClientOutDir()! // there, the path goes wrong
  // console.log(ctx.clientOutDir) => {rep_path}/dist
  ctx.basePathRelDir = ctx
    .qwikCityPlugin!.api.getBasePathname()
    .replace(/^\/|\/$/, "");
  ctx.clientOutBaseDir = join(ctx.clientOutDir, ctx.basePathRelDir);
  ctx.swClientDistPath = join(ctx.clientOutBaseDir, "service-worker.js");
  // [...]

Build fails on Cloudflare

App builds fine locally, but fails when deploying to Cloudflare pages.


12:56:10.989 | dist/service-worker.js                  21.08 kB │ gzip:  7.16 kB
-- | --
12:56:10.989 | dist/build/q-d0460e7d.js                52.22 kB │ gzip: 21.25 kB
12:56:10.990 | dist/build/q-0ebf9871.js                55.96 kB │ gzip: 13.85 kB
12:56:10.990 | dist/build/q-200ecef0.js                57.65 kB │ gzip:  7.95 kB
12:56:10.990 | dist/build/q-1760a7a4.js                60.98 kB │ gzip: 26.08 kB
12:56:10.990 | dist/build/q-d1a101c5.js                61.37 kB │ gzip:  8.90 kB
12:56:10.990 | dist/build/q-7a022fc6.js                66.89 kB │ gzip: 11.95 kB
12:56:10.990 | ✓ built in 6.68s
12:56:10.992 | free(): invalid size
12:56:11.012 | Aborted
12:56:11.013 | npm ERR! Lifecycle script `build.client` failed with error:
12:56:11.014 | npm ERR! Error: command failed
12:56:11.015 | npm ERR!   in workspace: xxx/app
12:56:11.015 | npm ERR!   at location: /opt/buildhome/repo/packages/app
12:56:11.028 | npm ERR! Lifecycle script `build` failed with error:
12:56:11.028 | npm ERR! Error: command failed
12:56:11.029 | npm ERR!   in workspace: xxx/app
12:56:11.029 | npm ERR!   at location: /opt/buildhome/repo/packages/app
12:56:11.037 | Failed: Error while executing user command. Exited with error code: 1
12:56:11.048 | Failed: build command exited with code: 1
12:56:12.073 | Failed: error occurred while running build command

Only link with same error message I could find: https://stackoverflow.com/questions/49422220/error-in-free-invalid-size

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.