Skip to content

Commit

Permalink
feat: custom sw without injection point (#390)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
userquin and antfu committed Dec 12, 2022
1 parent ea1a58b commit e500d1a
Show file tree
Hide file tree
Showing 14 changed files with 523 additions and 439 deletions.
1 change: 1 addition & 0 deletions examples/vanilla-ts-dev-options/src/vite-env.ts
@@ -1,2 +1,3 @@
/// <reference types="vite/client" />
/// <reference types="vite-plugin-pwa/client" />
/// <reference types="vite-plugin-pwa/info" />
9 changes: 9 additions & 0 deletions examples/vanilla-ts-no-ip/README.md
@@ -0,0 +1,9 @@
# Example

This example relies on [https-localhost](https://github.com/daquinoaldo/https-localhost) to serve the dist files on https://localhost/. Please refer to it's docs for the steps to setup your local environment.

```bash
npm run start-sw
```

Open up https://localhost/ to check the PWA is working.
22 changes: 22 additions & 0 deletions examples/vanilla-ts-no-ip/index.html
@@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="/pwa-192x192.png">
<link rel="mask-icon" href="/favicon.svg" color="#FFFFFF">
<meta name="msapplication-TileColor" content="#FFFFFF">
<meta name="theme-color" content="#ffffff">
<title>Vite App</title>
<style>
#app {
text-align: center;
}
</style>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
24 changes: 24 additions & 0 deletions examples/vanilla-ts-no-ip/package.json
@@ -0,0 +1,24 @@
{
"name": "vanilla-ts-no-ip",
"version": "0.0.0",
"private": true,
"scripts": {
"dev": "rimraf dev-dist && cross-env DEBUG=vite-plugin-pwa:* SW_DEV=true vite --force",
"run-build-sw": "cross-env DEBUG=vite-plugin-pwa:* BASE_URL=/ SOURCE_MAP=true vite build",
"start-sw": "npm run run-build-sw && npm run serve",
"serve": "serve dist"
},
"devDependencies": {
"cross-env": "^7.0.3",
"rimraf": "^3.0.2",
"typescript": "^4.8.2",
"vite": "^3.1.0",
"vite-plugin-pwa": "workspace:*",
"workbox-cacheable-response": "^6.5.4",
"workbox-core": "^6.5.4",
"workbox-expiration": "^6.5.4",
"workbox-routing": "^6.5.4",
"workbox-strategies": "^6.5.4",
"workbox-window": "^6.5.4"
}
}
130 changes: 130 additions & 0 deletions examples/vanilla-ts-no-ip/public/favicon.svg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/vanilla-ts-no-ip/public/pwa-192x192.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/vanilla-ts-no-ip/public/pwa-512x512.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
66 changes: 66 additions & 0 deletions examples/vanilla-ts-no-ip/src/custom-sw.ts
@@ -0,0 +1,66 @@
import { clientsClaim } from 'workbox-core'
import { registerRoute } from 'workbox-routing'
import { CacheFirst, NetworkFirst, StaleWhileRevalidate } from 'workbox-strategies'
import { CacheableResponsePlugin } from 'workbox-cacheable-response'
import { ExpirationPlugin } from 'workbox-expiration'

declare let self: ServiceWorkerGlobalScope

self.skipWaiting()
clientsClaim()

if (import.meta.env.DEV) {
// Avoid caching on dev: force always go to the server
registerRoute(
() => true,
new NetworkFirst({
cacheName: 'all-dev',
plugins: [
new CacheableResponsePlugin({ statuses: [-1] }),
],
}),
)
}

if (import.meta.env.PROD) {
// Cache page navigations (html) with a Network First strategy
registerRoute(
({ request }) => {
return request.mode === 'navigate'
},
new NetworkFirst({
cacheName: 'pages',
plugins: [
new CacheableResponsePlugin({ statuses: [200] }),
],
}),
)

// Cache CSS, JS, and Web Worker requests with a Stale While Revalidate strategy
registerRoute(
({ request }) =>
request.destination === 'style'
|| request.destination === 'manifest'
|| request.destination === 'script'
|| request.destination === 'worker',
new StaleWhileRevalidate({
cacheName: 'assets',
plugins: [
new CacheableResponsePlugin({ statuses: [200] }),
],
}),
)

// Cache images with a Cache First strategy
registerRoute(
({ request }) => request.destination === 'image',
new CacheFirst({
cacheName: 'images',
plugins: [
new CacheableResponsePlugin({ statuses: [200] }),
// 50 entries max, 30 days max
new ExpirationPlugin({ maxEntries: 50, maxAgeSeconds: 60 * 60 * 24 * 30 }),
],
}),
)
}
33 changes: 33 additions & 0 deletions examples/vanilla-ts-no-ip/src/main.ts
@@ -0,0 +1,33 @@
import { pwaInfo } from 'virtual:pwa-info'
import { registerSW } from 'virtual:pwa-register'

const date = __DATE__

// eslint-disable-next-line no-console
console.log(pwaInfo)

const app = document.querySelector<HTMLDivElement>('#app')!

app.innerHTML = `
<div>
<img src="/favicon.svg" alt="PWA Logo" width="60" height="60">
<h1>Vite + TypeScript</h1>
<p>Testing SW without <b>Injection Point (self.__WB_MANIFEST)</b></p>
<br/>
<p>${date}</p>
<br/>
</div>
`

registerSW({
immediate: true,
onNeedRefresh() {
// eslint-disable-next-line no-console
console.log('onNeedRefresh message should not appear')
},
onOfflineReady() {
// eslint-disable-next-line no-console
console.log('onOfflineReady message should not appear')
},
})

5 changes: 5 additions & 0 deletions examples/vanilla-ts-no-ip/src/vite-env.ts
@@ -0,0 +1,5 @@
/// <reference types="vite/client" />
/// <reference types="vite-plugin-pwa/client" />
/// <reference types="vite-plugin-pwa/info" />

declare const __DATE__: string
21 changes: 21 additions & 0 deletions examples/vanilla-ts-no-ip/tsconfig.json
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ESNext", "DOM", "WebWorker"],
"moduleResolution": "Node",
"strict": true,
"sourceMap": true,
"resolveJsonModule": true,
"isolatedModules": true,
"esModuleInterop": true,
"noEmit": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"skipLibCheck": true,
"types": ["vite-plugin-pwa", "vite-plugin-pwa/client", "vite-plugin-pwa/info"]
},
"include": ["src/**/*.ts"]
}
53 changes: 53 additions & 0 deletions examples/vanilla-ts-no-ip/vite.config.ts
@@ -0,0 +1,53 @@
import { defineConfig } from 'vite'
import { VitePWA } from 'vite-plugin-pwa'

export default defineConfig({
logLevel: 'info',
define: {
__DATE__: `'${new Date().toISOString()}'`,
},
build: {
sourcemap: process.env.SOURCE_MAP === 'true',
},
plugins: [
VitePWA({
mode: 'development',
base: '/',
strategies: 'injectManifest',
registerType: 'autoUpdate',
includeAssets: ['favicon.svg'],
filename: 'custom-sw.ts',
srcDir: 'src',
manifest: {
name: 'PWA Router',
short_name: 'PWA Router',
theme_color: '#ffffff',
icons: [
{
src: 'pwa-192x192.png', // <== don't add slash, for testing
sizes: '192x192',
type: 'image/png',
},
{
src: '/pwa-512x512.png', // <== don't remove slash, for testing
sizes: '512x512',
type: 'image/png',
},
{
src: 'pwa-512x512.png', // <== don't add slash, for testing
sizes: '512x512',
type: 'image/png',
purpose: 'any maskable',
},
],
},
injectManifest: {
injectionPoint: undefined,
},
devOptions: {
enabled: process.env.SW_DEV === 'true',
type: 'module',
},
}),
],
})

0 comments on commit e500d1a

Please sign in to comment.