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

fix(pwa): Fix offline functionality #350

Merged
merged 4 commits into from
Jun 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions app.vue
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
<script setup lang="ts">
import { swPath } from 'virtual:pwa'
import { useSettings } from '~~/stores/settings'

if (!process.server) {
Expand All @@ -23,8 +22,8 @@ if (!process.server) {
if (typeof window !== 'undefined') {
if ('serviceWorker' in navigator) {
const registerSw = () => {
console.debug(`Registering service worker at /${swPath}`)
navigator.serviceWorker.register(`/${swPath}`)
console.debug('Registering service worker at /serviceworker.js')
navigator.serviceWorker.register('/serviceworker.js')
}

if (document.readyState === 'complete') {
Expand Down
2 changes: 1 addition & 1 deletion modules/build/icon_resize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export default function IconResizer (moduleOptions: IconResizerPluginOptions): P
return new Promise((_resolve, reject) => reject(new Error('No source file specified')))
}

const outputFolder = join(config.build.outDir, moduleOptions.outputFolder)
const outputFolder = join(config.publicDir, moduleOptions.outputFolder)

if (!existsSync(outputFolder)) {
mkdirSync(outputFolder, { recursive: true })
Expand Down
49 changes: 37 additions & 12 deletions modules/build/pwa.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import path from 'path'
import { PluginOption } from 'vite'
import { rmSync, readdirSync } from 'fs'
import { generateSW } from 'workbox-build'
import { type PluginOption } from 'vite'

interface PWAModuleOptions {
swPath: string
Expand All @@ -14,13 +15,13 @@ export default function VitePWAGenerator (moduleOptions: PWAModuleOptions): Plug

return {
name: 'Workbox installer',
resolveId (id) {
resolveId (id: string) {
// register virtual module
if (id === virtualModuleId) {
return resolvedVirtualModuleId
}
},
load (id) {
load (id: string) {
// return virtual module
if (id === resolvedVirtualModuleId) {
return `export const swPath = '${swPath}'`
Expand All @@ -32,39 +33,63 @@ export default function VitePWAGenerator (moduleOptions: PWAModuleOptions): Plug
return
}

const outputDir = config.publicDir
readdirSync(outputDir).filter(file => file.startsWith('workbox-')).forEach((file) => {
console.info(`Removing ${path.join(outputDir, file)}`)
rmSync(path.join(outputDir, file))
})

await generateSW({
swDest: path.join(config.build.outDir, swPath),
globDirectory: config.build.outDir,
swDest: path.join(outputDir, moduleOptions.swPath),
globDirectory: outputDir,
globPatterns: [
'**/*.{js,mjs,css,html}'
'**/*.{js,json,mjs,css,html,svg,woff2}'
],
sourcemap: false,
navigationPreload: true,
runtimeCaching: [
{
urlPattern: '*.js',
handler: 'StaleWhileRevalidate',
urlPattern: ({ url }) => /\.(js|json|css)$/.exec(url.pathname) !== null,
handler: 'CacheFirst',
options: {
cacheName: 'code',
cacheableResponse: {
statuses: [0, 200]
}
}
},
{
urlPattern: '*.css',
urlPattern: ({ url }) => /\.(jpg|png|jpeg|svg)$/.exec(url.pathname) !== null,
handler: 'CacheFirst',
options: {
cacheName: 'assets',
cacheableResponse: {
statuses: [200]
}
}
},
{
urlPattern: ({ url }) => /\.(woff2)$/.exec(url.pathname) !== null,
handler: 'StaleWhileRevalidate',
options: {
cacheName: 'fonts',
cacheableResponse: {
statuses: [0, 200]
}
}
},
{
urlPattern: '*.{jpg,png,jpeg}',
handler: 'CacheFirst'
urlPattern: ({ url }) => ['', '/', '/index', '/index.html'].includes(url.pathname),
handler: 'NetworkFirst',
options: {
cacheableResponse: {
statuses: [0, 200]
}
}
}
]
})
console.info(`Generated service worker at ${path.join(config.build.outDir, swPath)}`)
console.info(`Generated service worker at ${path.join(outputDir, moduleOptions.swPath)}`)
}
}
}
8 changes: 4 additions & 4 deletions nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import { dirname, resolve } from 'path'
import { fileURLToPath } from 'url'
import VueI18nVitePlugin from '@intlify/unplugin-vue-i18n/vite'
import StylelintPlugin from 'vite-plugin-stylelint'
import VitePWAGenerator from './modules/build/pwa'
import IconResizer from './modules/build/icon_resize'
import ServiceWorkerGenerator from './modules/build/pwa'
import { AppPlatform } from './platforms/platforms'

const packageJson = fs.readFileSync('./package.json').toString()
Expand Down Expand Up @@ -188,8 +188,8 @@ export default defineNuxtConfig({
families: {
Lexend: [400, 700]
},
display: 'swap'
// download: true
display: 'swap',
download: false
},

/*
Expand Down Expand Up @@ -235,7 +235,7 @@ export default defineNuxtConfig({
resolve(dirname(fileURLToPath(import.meta.url)), './i18n/en.json')
]
}),
VitePWAGenerator({ swPath: 'serviceworker.js' }),
ServiceWorkerGenerator({ swPath: 'serviceworker.js' }),
IconResizer(iconConfig),
IconResizer({
outputFolder: 'icons',
Expand Down
4 changes: 4 additions & 0 deletions public/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# these are files generated during builds
serviceworker.js
workbox-*.js
icons/