vite-pwa / sveltekit Goto Github PK
View Code? Open in Web Editor NEWZero-config PWA Plugin for SvelteKit
Home Page: https://vite-pwa-org.netlify.app/frameworks/sveltekit
License: MIT License
Zero-config PWA Plugin for SvelteKit
Home Page: https://vite-pwa-org.netlify.app/frameworks/sveltekit
License: MIT License
The generated asset links on dynamic pages are relative to the current directory instead of the root, resulting in prefixing the current URL to the asset requests which do not exist.
Navigating to pages with the client side router works correctly. The only problem is when you open the page to a page that isn't prerendered or refresh the page on a page that isn't prerendered that you encounter the problem.
I've tested the normal example produced with npm create svelte@latest my-app
and it correctly generates relative links to the assets.
Issue reproduction: https://github.com/meticoeus/sveltekit. See the modified example
$ cd ./examples/sveltekit-ts
$ npm i
$ npm run build
$ npm run preview
# navigate to http://localhost:4173/about/foo
# you may need to refresh the page to ensure you are loading the file from the server/service worker cache instead of the client side router.
I've made minimum modifications to the example to switch to the new auto adapter and add a dynamic route page that imports a component to show the problem.
Example generated html for route /about/[id]
in .svelte-kit/output/
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="./favicon.svg" type="image/svg+xml" />
<link rel="alternate icon" href="./favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<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">
<meta http-equiv="content-security-policy" content="">
<!-- ↓ Notice the './' here instead of '../'-->
<link href="./_app/immutable/assets/_layout-7c064e52.css" rel="stylesheet">
<link href="./_app/immutable/assets/ReloadPrompt-1dacdefd.css" rel="stylesheet">
<link href="./_app/immutable/assets/_page-fefd3e3e.css" rel="stylesheet">
<link href="./_app/immutable/assets/Counter-28c380d8.css" rel="stylesheet">
<link rel="modulepreload" href="./_app/immutable/start-50acbb5f.js">
<link rel="modulepreload" href="./_app/immutable/chunks/index-606a435a.js">
<link rel="modulepreload" href="./_app/immutable/chunks/singletons-006c2a7a.js">
<link rel="modulepreload" href="./_app/immutable/chunks/index-6d6f5695.js">
<link rel="modulepreload" href="./_app/immutable/chunks/preload-helper-f8376bb0.js">
<link rel="modulepreload" href="./_app/immutable/components/pages/_layout.svelte-607721bf.js">
<link rel="modulepreload" href="./_app/immutable/chunks/stores-83e7464f.js">
<link rel="modulepreload" href="./_app/immutable/modules/pages/_layout.ts-fa3c4266.js">
<link rel="modulepreload" href="./_app/immutable/chunks/_layout-9a8b0c19.js">
<link rel="modulepreload" href="./_app/immutable/components/pages/_page.svelte-6e5f7367.js">
<link rel="modulepreload" href="./_app/immutable/chunks/Counter-1b9396a8.js">
<link rel="modulepreload" href="./_app/immutable/modules/pages/_page.ts-ed610ca4.js">
<link rel="modulepreload" href="./_app/immutable/chunks/_page-de0ef88a.js"><title>Home</title><!-- HEAD_svelte-hnr6zt_START --><!-- HTML_TAG_START --><link rel="manifest" href="/manifest.webmanifest"><!-- HTML_TAG_END --><!-- HEAD_svelte-hnr6zt_END --><!-- HEAD_svelte-t32ptj_START --><meta name="description" content="Svelte demo app"><!-- HEAD_svelte-t32ptj_END -->
</head>
<body>
<div>
<header class="svelte-1wxubj"><div class="corner svelte-1wxubj"><a href="https://kit.svelte.dev" class="svelte-1wxubj"><img src="/_app/immutable/assets/svelte-logo-87df40b8.svg" alt="SvelteKit" class="svelte-1wxubj"></a></div>
<nav data-sveltekit-prefetch class="svelte-1wxubj"><svg viewBox="0 0 2 3" aria-hidden="true" class="svelte-1wxubj"><path d="M0,0 L1,2 C1.5,3 1.5,3 2,3 L2,0 Z" class="svelte-1wxubj"></path></svg>
<ul class="svelte-1wxubj"><li class="svelte-1wxubj active"><a href="/" class="svelte-1wxubj">Home</a></li>
<li class="svelte-1wxubj"><a href="/about" class="svelte-1wxubj">About</a></li></ul>
<svg viewBox="0 0 2 3" aria-hidden="true" class="svelte-1wxubj"><path d="M0,0 L0,3 C0.5,3 0.5,3 1,2 L2,0 Z" class="svelte-1wxubj"></path></svg></nav>
<div class="corner svelte-1wxubj">2023-02-01T23:45:27.577Z</div>
</header>
<main class="svelte-1izrdc8">
<section class="svelte-1egtvge"><h1 class="svelte-1egtvge"><span class="welcome svelte-1egtvge"><picture><source srcset="svelte-welcome.webp" type="image/webp">
<img src="svelte-welcome.png" alt="Welcome" class="svelte-1egtvge"></picture></span>
to your new<br>SvelteKit app
</h1>
<h2>try editing <strong>src/routes/+page.svelte</strong></h2>
<div class="counter svelte-sx9eo4"><button aria-label="Decrease the counter by one" class="svelte-sx9eo4"><svg aria-hidden="true" viewBox="0 0 1 1" class="svelte-sx9eo4"><path d="M0,0.5 L1,0.5" class="svelte-sx9eo4"></path></svg></button>
<div class="counter-viewport svelte-sx9eo4"><div class="counter-digits svelte-sx9eo4" style="transform: translate(0, 0%)"><strong class="hidden svelte-sx9eo4" aria-hidden="true">1</strong>
<strong class="svelte-sx9eo4">0</strong></div></div>
<button aria-label="Increase the counter by one" class="svelte-sx9eo4"><svg aria-hidden="true" viewBox="0 0 1 1" class="svelte-sx9eo4"><path d="M0,0.5 L1,0.5 M0.5,0 L0.5,1" class="svelte-sx9eo4"></path></svg></button>
</div>
</section></main>
<footer class="svelte-1izrdc8"><p>visit <a href="https://kit.svelte.dev" class="svelte-1izrdc8">kit.svelte.dev</a> to learn SvelteKit</p></footer>
<script type="module" data-sveltekit-hydrate="kstxm9">
import { start } from "./_app/immutable/start-50acbb5f.js";
start({
env: {},
paths: {"assets":"","base":""},
target: document.querySelector('[data-sveltekit-hydrate="kstxm9"]').parentNode,
version: "1675295127372",
hydrate: {
node_ids: [0, 2],
data: [null,null],
form: null,
error: null
}
});
</script>
</div>
</body>
</html>
I just updated all my Sveltekit dependencies to their latest versions and it broke this plugin (also updated to latest version).
Relevant stack trace on trying to build my previously functioning app:
files generated
.svelte-kit/output/server/sw.js
.svelte-kit/output/server/workbox-6644f8fd.js
warnings
One of the glob patterns doesn't match any files. Please remove or fix the following: {
"globDirectory": "[...app path]/.svelte-kit/output",
"globPattern": "client/**/*.{js,css,ico,png,svg,webp,webmanifest}",
"globIgnores": [
"**/node_modules/**/*",
"server/sw.js",
"server/workbox-*.js"
]
}
[vite-plugin-pwa:sveltekit:build] ENOENT: no such file or directory, open [...app path]/.svelte-kit/output/client/sw.js
Package versions:
PWA config:
This isn't an issue with vite-pwa specifically, but I'm putting it here for future people who are trying to search the web, and hopefully it can be indexed by a search engine too (as I spent quite a few hours trying to figure this one out). When generating large Sveltekit apps, the automatically generated _routes.json can become too large, and when it goes over 100 entries, it will 'chop-off' anything past the 100. This can include the service worker and manifest files generated by vite-pwa, and when Cloudflare tries to serve these as a function (instead of static file), they return a 404, which breaks the PWA/Service Worker.
Additionally, I've found that somewhere in the process of generating _routes.json (haven't been able to pin point where/which project), the sw.js, workbox-<>.js and manifest.webmanifest files aren't automatically added to this list in the first place. So for anyone having issues, the easiest way is to manually define the routes.
I've pasted part of my svelte.config.js below for reference. I've notably excluded the <files> shorthand, as my app has a lot of static files which would go over the 100 entry limit, and have instead manually added these (and they can work with wildcards too - like the /fonts/* and /images/*).
const config = {
kit: {
adapter: adapter({
routes: {
include: ['/*'],
exclude: ['<build>', '<prerendered>', '/fonts/*', '/images/*', '/favicon.ico', '/robots.txt', '/favicon.png', '/sw.js', '/workbox-fa446783.js', '/manifest.webmanifest']
}
}),
serviceWorker: {
register: false
}
}
};
When building the application manifest.webmanifest file is added twice to cached file list, that causes an error and the app become unavailable offline.
I created a repo using the official sveltekit skeleton app and a minimal configuration that you can use to verify the problem. You just need to build and preview the application to obtain the error:
Uncaught (in promise) add-to-cache-list-conflicting-entries: add-to-cache-list-conflicting-entries
We also need to change the docs in the vite-pplugin-pwa
: we have a few entries here vite-pwa/vite-plugin-pwa#327
also change the link to the home page linking to the kit entry in docs: in gh about entry
I'm using @sveltejs/kit 1.0.0-next.520, vite 3.1.8 and have installed this package as: "@vite-pwa/sveltekit": "github:vite-pwa/sveltekit".
When running dev or build, I get the following error:
[ERROR] [plugin externalize-deps] Failed to resolve entry for package "@vite-pwa/sveltekit". The package may have incorrect main/module/exports specified in its package.json.
node_modules/.pnpm/[email protected]/node_modules/esbuild/lib/main.js:1327:27:
1327 │ let result = await callback({
╵ ^
at packageEntryFailure (file:///home/robhicks/dev/savvagent/budget-kit/node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-4da11a5e.js:34841:11)
at resolvePackageEntry (file:///home/robhicks/dev/savvagent/budget-kit/node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-4da11a5e.js:34838:5)
at tryNodeResolve (file:///home/robhicks/dev/savvagent/budget-kit/node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-4da11a5e.js:34584:20)
at file:///home/robhicks/dev/savvagent/budget-kit/node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-4da11a5e.js:63472:44
at requestCallbacks.on-resolve (/home/robhicks/dev/savvagent/budget-kit/node_modules/.pnpm/[email protected]/node_modules/esbuild/lib/main.js:1327:28)
at handleRequest (/home/robhicks/dev/savvagent/budget-kit/node_modules/.pnpm/[email protected]/node_modules/esbuild/lib/main.js:697:19)
at handleIncomingPacket (/home/robhicks/dev/savvagent/budget-kit/node_modules/.pnpm/[email protected]/node_modules/esbuild/lib/main.js:719:7)
at Socket.readFromStdout (/home/robhicks/dev/savvagent/budget-kit/node_modules/.pnpm/[email protected]/node_modules/esbuild/lib/main.js:647:7)
at Socket.emit (node:events:513:28)
at addChunk (node:internal/streams/readable:324:12)
This error came from the "onResolve" callback registered here:
node_modules/.pnpm/[email protected]/node_modules/esbuild/lib/main.js:1251:20:
1251 │ let promise = setup({
╵ ^
at setup (file:///home/robhicks/dev/savvagent/budget-kit/node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-4da11a5e.js:63465:27)
at handlePlugins (/home/robhicks/dev/savvagent/budget-kit/node_modules/.pnpm/[email protected]/node_modules/esbuild/lib/main.js:1251:21)
at buildOrServeImpl (/home/robhicks/dev/savvagent/budget-kit/node_modules/.pnpm/[email protected]/node_modules/esbuild/lib/main.js:942:5)
at Object.buildOrServe (/home/robhicks/dev/savvagent/budget-kit/node_modules/.pnpm/[email protected]/node_modules/esbuild/lib/main.js:750:5)
at /home/robhicks/dev/savvagent/budget-kit/node_modules/.pnpm/[email protected]/node_modules/esbuild/lib/main.js:2085:17
at new Promise (<anonymous>)
at Object.build (/home/robhicks/dev/savvagent/budget-kit/node_modules/.pnpm/[email protected]/node_modules/esbuild/lib/main.js:2084:14)
at build (/home/robhicks/dev/savvagent/budget-kit/node_modules/.pnpm/[email protected]/node_modules/esbuild/lib/main.js:1931:51)
at bundleConfigFile (file:///home/robhicks/dev/savvagent/budget-kit/node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-4da11a5e.js:63432:26)
The plugin "externalize-deps" was triggered by this import
vite.config.js:4:29:
4 │ import { SvelteKitPWA } from '@vite-pwa/sveltekit'
╵ ~~~~~~~~~~~~~~~~~~~~~
My vite.config.js file looks like this:
import { resolve } from 'path'
import { sveltekit } from '@sveltejs/kit/vite';
import { SvelteKitPWA } from '@vite-pwa/sveltekit'
const config = {
plugins: [
sveltekit(),
SvelteKitPWA({
devOptions: { enabled: false },
includeAssets: ['favicon.png', 'apple-touch-icon-180x180.png', 'mask-icon.svg'],
manifest: {
background_color: '#FFFFFF',
name: 'Savvagent Budgets',
short_name: 'Budgets',
theme_color: '#FFFFFF',
icons: [
{ src: 'logo-192.png', sizes: '192x192', type: 'image/png' },
{ src: 'logo-512.png', sizes: '512x512', type: 'image/png', purpose: 'any maskable' }
]
},
registerType: 'autoUpdate'
})
],
resolve: {
alias: {
$components: resolve('src', 'components'),
$stores: resolve('src', 'stores'),
$utils: resolve('src', 'utils'),
}
}
};
export default config;
Importing virtual:pwa-register
in +layout.svelte
causes bug during build:
[vite-plugin-pwa:sveltekit:build] The 'swSrc' file can't be read. ENOENT: no such file or directory, open '.svelte-kit/output/client/service-worker.js'
error during build:
Error: The 'swSrc' file can't be read. ENOENT: no such file or directory, open '.svelte-kit/output/client/service-worker.js'
at injectManifest (node_modules/.pnpm/[email protected]/node_modules/workbox-build/build/inject-manifest.js:71:15)
at async Object.handler (file://node_modules/.pnpm/@[email protected]_@[email protected][email protected]/node_modules/@vite-pwa/sveltekit/dist/index.mjs:189:31)
at async PluginDriver.hookParallel (file://node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/node-entry.js:25338:17)
at async file://node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/node-entry.js:26578:13
at async catchUnfinishedHookActions (file://node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/node-entry.js:25782:16)
at async rollupInternal (file://node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/node-entry.js:26565:5)
at async build (file://node_modules/.pnpm/[email protected]_@[email protected][email protected]/node_modules/vite/dist/node/chunks/dep-75f53616.js:47956:18)
at async CAC.<anonymous> (file://node_modules/.pnpm/[email protected]_@[email protected][email protected]/node_modules/vite/dist/node/cli.js:822:9)
ELIFECYCLE Command failed with exit code 1.
Inspecting .svelte-kit/output/client/ i can see that there is no service-worker.js or sw.js file when the error is thrown.
It works running locally and if i comment out the import
import { registerSW } from 'virtual:pwa-register';
it works to build the app.
vite.config.ts:
const globPatterns = [
'client/**/*.{js,css,ico,png,svg,webp,woff,woff2}',
];
sveltekitPWA({
base: '/',
devOptions: {
enabled: true,
navigateFallback: '/',
type: 'module',
},
filename: 'sw.ts',
injectManifest: {
globPatterns,
},
injectRegister: null,
kit: {},
manifest: {
background_color: '#ffffff',
description: 'MailVideo Admin Dashboard',
display: 'standalone',
icons: [
{
sizes: '192x192',
src: '/pwa-192x192.png',
type: 'image/png',
},
{
sizes: '512x512',
src: '/pwa-512x512.png',
type: 'image/png',
},
{
purpose: 'any maskable',
sizes: '512x512',
src: '/pwa-512x512.png',
type: 'image/png',
},
],
name: `MailVideo Admin${mailVideoPrefix}`,
scope: '/',
short_name: `MailVideo Admin${mailVideoPrefix}`,
start_url: '/',
theme_color: '#277BFA',
},
registerType: 'autoUpdate',
scope: '/',
srcDir: './src',
strategies: 'injectManifest',
workbox: {
globPatterns,
},
}),
sw.ts:
/// <reference types="@sveltejs/kit" />
/// <reference no-default-lib="true"/>
/// <reference lib="esnext" />
/// <reference lib="webworker" />
import { type FirebaseOptions, initializeApp } from 'firebase/app';
import { getMessaging } from 'firebase/messaging/sw';
import { clientsClaim } from 'workbox-core';
import { cleanupOutdatedCaches, precacheAndRoute } from 'workbox-precaching';
declare let self: Omit<ServiceWorkerGlobalScope, '__WB_MANIFEST'> & {
__WB_MANIFEST?: ServiceWorkerGlobalScope['__WB_MANIFEST'];
skipWaiting(): Promise<void>;
};
// https://vite-pwa-org.netlify.app/guide/inject-manifest.html#service-worker-code
// self.__WB_MANIFEST is default injection point
precacheAndRoute(self.__WB_MANIFEST ?? []);
// clean old assets
cleanupOutdatedCaches();
// Auto update: https://vite-pwa-org.netlify.app/guide/inject-manifest.html#auto-update-behavior
void self.skipWaiting();
clientsClaim();
svelte.config.js
/** @type {import('@sveltejs/kit').Config} */
const config = {
...
kit: {
serviceWorker: {
register: false,
},
files: {
serviceWorker: 'src/sw.ts',
},
adapter: adapter({
runtime: 'nodejs18.x',
}),
}
};
export default config;
Versions:
@vite-pwa/sveltekit: 0.2.5
@sveltejs/kit: 1.22.4
vite: 4.4.8
the hero image should be for SvelteKit, like the title: Zero-config PWA Plugin for SvelteKit
@antfu do you like that change? If so, can you change/provide the hero image?
Using generateSW
for my service worker, when I boot up a new build and do a page refresh or navigate to a route that throws a SvelteKit error (either from a load function in +page.ts
or just a missing route), the client seems to get stuck in an infinite loop of navigating to the same page that generated the error and requesting /_app/version.json
from the server.
Workbox repeatedly reports a full page navigation in the log (always to the same page) and triggering the associated invalidation of page data, and eventually things get halted by Chrome navigation throttling.
The issue only occurs on routes that throw errors from a +page.ts
load function or are missing entirely (triggering the SvelteKit fallback error page). If I "start" on any non-error-generating page and only navigate to the error-generating one after the update, error handling works as normal again. Same goes for offline mode (since no new SW versions are found).
Service workers are still pretty new to me, so I haven't been able to identify what could be the trigger of this conflict between the fetch of new updates and SvelteKit errors. I would have assumed the behavior of purely client-side +error.svelte
/ +page.load
interactions would behave similarly to just in-lining an {#if error} ...
page in page.svelte
, yet one plays nice with the service worker and the other does not.
I've been able to replicate it both in local builds and deployed builds on Vercel, so can exclude that it's related to http vs. https or any other local dev environment factors. Happy to provide more info / reproduce in a fresh repo if needed, otherwise will post here if I find a fix.
I'm getting an error when using this package "@vite-pwa/sveltekit": "0.2.1"
with a freshly created project using "@sveltejs/kit": "^1.5.0"
. Can anyone please let me know if these versions are incompatible?
I have setup the basic config file following the documentation describes:
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
import { SvelteKitPWA } from '@vite-pwa/sveltekit';
export default defineConfig({
plugins: [sveltekit(), SvelteKitPWA()]
});
Below is the run time error:
failed to load config from /Users/.../sveltekit-app/vite.config.ts
error when starting dev server:
Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'vite-plugin-pwa' imported from /Users/.../sveltekit-app/node_modules/@vite-pwa/sveltekit/dist/index.mjs
at new NodeError (node:internal/errors:387:5)
at packageResolve (node:internal/modules/esm/resolve:852:9)
at moduleResolve (node:internal/modules/esm/resolve:901:20)
at defaultResolve (node:internal/modules/esm/resolve:1115:11)
at nextResolve (node:internal/modules/esm/loader:163:28)
at ESMLoader.resolve (node:internal/modules/esm/loader:837:30)
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:424:18)
at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:76:40)
at link (node:internal/modules/esm/module_job:75:36)
error Command failed with exit code 1.
I tried to pass rollup plugins to my build of injectManifest like this, which is what the type is describing:
import replace from '@rollup/plugin-replace';
import terser from '@rollup/plugin-terser';
SvelteKitPWA({
strategies: 'injectManifest',
// // this affect whether workbox output log and the bundle is minified or not
// mode: "development",
mode: "production",
registerType: "prompt",
injectManifest: {
globIgnores: ["server/**", "**/*.{css,js}"],
globPatterns: ["**/*.{ico,jpg,jpeg,png,svg,woff,woff2}"],
plugins: [
replace({
'process.env.NODE_ENV': JSON.stringify('production')
}),
terser()
]
}
})
But then I get this error:
Error: [InjectManifest] 'plugins' property is not expected to be here.
I am using "@vite-pwa/sveltekit": "0.2.7",
SvelteKit 1.3.1 change: SSR build happens before the client-side build
When navigating to missing routes (404
) within the example project, the home page (/
) is rendered instead.
I've adopted almost the same configuration and service worker script for a personal project.
I've noticed that the service worker even redirects server routes (+server.ts
) to /
.
I think that the issue lies within the following lines within the service worker script:
sveltekit/examples/sveltekit-ts/src/prompt-sw.ts
Lines 21 to 29 in c6c3499
When getting rid of these lines from my personal project, I no longer run into this issue.
404
error page+server.ts
routes behave as expectedNote
I've also run a Lighthouse test to check that the PWA functionality isn't compromised.
When previewing locally, when offline, the service worker performs as expected.
I would appreciate it if some more context could be added as to why these lines are required.
Thank you for your time.
Building a SvelteKit application with latest @vite-pwa/sveltekit
fails out of the box with the following error:
error during build:
Error [PLUGIN_ERROR]: Cannot find package 'kolorist' imported from C:\xx\xx\sveltekit-sample\node_modules\@vite-pwa\sveltekit\dist\chunks\log.mjs
at new NodeError (node:internal/errors:399:5)
at packageResolve (node:internal/modules/esm/resolve:889:9)
at moduleResolve (node:internal/modules/esm/resolve:938:20)
at defaultResolve (node:internal/modules/esm/resolve:1153:11)
at nextResolve (node:internal/modules/esm/loader:163:28)
at ESMLoader.resolve (node:internal/modules/esm/loader:838:30)
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:424:18)
at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:77:40)
at link (node:internal/modules/esm/module_job:76:36)
My package versions:
"@sveltejs/kit": "1.15.0"
"@vite-pwa/sveltekit": "2.0.1"
"vite-pwa-plugin": "0.14.7"
After installing kolorist
manually everything works fine.
So in order to fix this, kolorist
should be added to dependencies
and removed from devDependencies
in package.json
of @vite-pwa/sveltekit
.
My service worker under src/service-worker.ts
:
import { precacheAndRoute } from 'workbox-precaching';
declare const self: ServiceWorkerGlobalScope;
precacheAndRoute(self.__WB_MANIFEST);
My Vite config:
import { sveltekit } from '@sveltejs/kit/vite';
import { SvelteKitPWA } from '@vite-pwa/sveltekit';
/** @type {import('vite').UserConfig} */
const config = {
plugins: [
sveltekit(),
SvelteKitPWA({
strategies: 'injectManifest'
})
],
test: {
include: ['src/**/*.{test,spec}.{js,ts}']
},
// see https://vite-pwa-org.netlify.app/frameworks/sveltekit.html#generate-custom-service-worker
define: {
'process.env.NODE_ENV': process.env.NODE_ENV === 'production'
? '"production"'
: '"development"'
}
};
export default config;
SvelteKit is finally 1.0.0. Alas, adding the PWA functionality fails again. :'(
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/vite
npm ERR! dev vite@"^4.0.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer vite@"^3.1.0" from [email protected]
npm ERR! node_modules/vite-plugin-pwa
npm ERR! peer vite-plugin-pwa@"^0.13.3" from @vite-pwa/[email protected]
npm ERR! node_modules/@vite-pwa/sveltekit
npm ERR! dev @vite-pwa/sveltekit@"0.0.1" from the root project
Is Vite 4 support in the pipelines?
Thanks, guys!
First of all I'd like to thank you very much for your effort on bringin Workbox support to Sveltekit ❤️
I've been playing around with @vite-pwa/sveltekit
the last couple of days and it's a great addition to the framework.
From what I can read in the docs, Vite PWA basically supports injectManifest
strategy in development.
However in SvelteKit, self.__WB_MANIFEST
is not replaced when running in development via npm run dev
. Therefore an error is thrown:
Is this the expected behaviour or a current limitation of SvelteKit's service worker build?
Also I noticed, that the service worker is always running in development regardless of wether enabled
is true
or false
in devOptions
.
As soon as running in preview via npm run preview
everything works perfectly fine.
src/service-worker.ts
:
/// <reference types="@sveltejs/kit" />
import { build, files, version } from '$service-worker';
import { cleanupOutdatedCaches, precacheAndRoute } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { NetworkFirst } from 'workbox-strategies';
declare const self: ServiceWorkerGlobalScope;
cleanupOutdatedCaches();
precacheAndRoute(self.__WB_MANIFEST);
registerRoute(
({ url }) => true,
new NetworkFirst({ cacheName: `runtime-cache-${version}`, networkTimeoutSeconds: 45 })
);
vite.config.js
:
import { sveltekit } from '@sveltejs/kit/vite';
import { SvelteKitPWA } from '@vite-pwa/sveltekit';
/** @type {import('vite').UserConfig} */
const config = {
plugins: [
sveltekit(),
SvelteKitPWA({
strategies: 'injectManifest',
// see https://vite-pwa-org.netlify.app/guide/inject-manifest.html#development
devOptions: {
enabled: true
}
})
],
test: {
include: ['src/**/*.{test,spec}.{js,ts}']
},
// see https://vite-pwa-org.netlify.app/frameworks/sveltekit.html#generate-custom-service-worker
define: {
'process.env.NODE_ENV': process.env.NODE_ENV === 'production'
? '"production"'
: '"development"'
}
};
export default config;
It generated some index.html files, but in sw.js file, all index.html miss .html
(for example, the highlight one).
In browser, it display an error:
sw.js:1 Uncaught (in promise) bad-precaching-response: bad-precaching-response :: [{"url":"https://10.1.1.1/dashboard/index","status":404}]
because the true path is dashboar/index.html.
sveltekitpwa config:
SvelteKitPWA({ base: '/', scope: '/', srcDir: 'src', strategies: 'injectManifest', filename: 'sw.ts', registerType: 'autoUpdate', // injectRegister: 'inline', injectManifest: { globPatterns: ["client/*.{html,css,js,jpg,png,ico,svg,webp,json,webmanifest}"] }, manifest: { name: "app", short_name: "app", description: "app", related_applications: [{ "platform": "windows", "url": `${prod_url}/manifest.webmanifest`, }, { "platform": "chrome_web_store", "url": `${prod_url}/manifest.webmanifest`, }], scope: "/", start_url: '/', theme_color: "#93b5cf", background_color: "#ebe7e7", display: 'standalone', 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', }, ], }, devOptions: { enabled: true, type: 'module', navigateFallback: '/' }, // if you have shared info in svelte config file put in a separate module and use it also here kit: {} } )]
I remove injectManifest:
configuration, no change for any index url, how to fix it?
Thx!
I found that PWA sveltekit runs before prerendered pages are generated, so those pages are not included in the manifest. Maybe this issue is related to sveltekit updates, I didn't see this warning before.
My current dependency versions:
"devDependencies": {
"@sveltejs/adapter-node": "^1.1.7",
"@sveltejs/kit": "^1.5.0",
"@vite-pwa/sveltekit": "^0.1.2",
"svelte": "^3.55.1",
"svelte-check": "^3.0.3",
"vite": "^4.1.1",
"vite-plugin-pwa": "^0.14.1",
"workbox-window": "^6.5.4"
},
I'm trying to create a static PWA with vite-pwa and deploy it to GitHub Pages.
Code: https://github.com/bassjoe/pwa5
Result: https://bassjoe.github.io/pwa5/
In Chrome's Developer Tools (F12), I see in the Network tab, that index.js, service worker and the manifest are not loading properly (404). The latter two work for the root /pwa5/
, but not for sub-routes like /pwa5/about/
(+F5).
For the manifest I can see that the generated index.html contains the correct path to the manifest file:
<link rel="manifest" href="/pwa5/manifest.webmanifest">
(https://github.com/bassjoe/pwa5/blob/gh-pages/about/index.html)
but when I look at the effective content in the Elements tab of the Developer Tools it looks like this:
<link rel="manifest" href="./manifest.webmanifest">
For a route like /pwa5/about/
this gives /pwa5/about/manifest.webmanifest
, which leads to the 404.
I can get the manifest path right by setting base: base + '/'
in vite.config.js, but it looks totally wrong and in the Application/Lighthouse tabs I see that the service worker is also not working correctly.
I was following the steps from here - https://vite-pwa-org.netlify.app/frameworks/sveltekit.html
I installed the dependency, added the plugin in the vite.config.js
and when I am adding the webmanifest link or the register SW code, I am seeing the problem that it is complaining about not able to find the module virtual:pwa-info
.
Based on what I see in the docs, I have tried adding the types
in my tsconfig. I also tried adding the references in my app.d.ts
file (as shown in this example - https://github.com/vite-pwa/sveltekit/blob/main/examples/sveltekit-ts/src/app.d.ts#L1 )
But neither have worked for me. VS Code still complains that the module is not found and in the run time It does have any pwaInfo
.
My +layout.svelte
<script lang="ts">
import '../app.postcss';
import { pwaInfo } from 'virtual:pwa-info';
import { onMount } from 'svelte';
onMount(async () => {
if (pwaInfo) {
// --->>>> It never get here.
const { registerSW } = await import('virtual:pwa-register');
if (registerSW) {
console.log('registering sw');
} else {
console.log('no sw');
}
registerSW({
immediate: true,
onRegistered(r: any) {
// uncomment following code if you want check for updates
// r && setInterval(() => {
// console.log('Checking for sw update')
// r.update()
// }, 20000 /* 20s for testing purposes */)
console.log(`SW Registered: ${r}`);
},
onRegisterError(error: any) {
console.log('SW registration error', error);
}
});
}
if (!pwaInfo) {
console.log('no pwa info'); // -->>>> I SEE THIS BEING LOGGED ON BROWSER CONSOLE.
}
});
$: webManifestLink = pwaInfo ? pwaInfo.webManifest.linkTag : '';
</script>
<svelte:head>
{@html webManifestLink}
</svelte:head>
<slot />
My vite.config.ts
import { sveltekit } from '@sveltejs/kit/vite';
import type { UserConfig } from 'vite';
import { SvelteKitPWA } from '@vite-pwa/sveltekit';
const config: UserConfig = {
plugins: [sveltekit(), SvelteKitPWA()],
test: {
include: ['src/**/*.{test,spec}.{js,ts}']
}
};
export default config;
My app.d.ts
:
// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
/// <reference types="vite-plugin-pwa/svelte" />
/// <reference types="vite-plugin-pwa/info" />
declare global {
namespace App {
// interface Error {}
interface Locals {
accessToken?: string;
user: {
userId: string;
email: string;
roles: string[];
name: string;
};
}
interface PageData {
user?: {
userId: string;
email: string;
roles: string[];
name: string;
};
}
// interface Platform {}
}
}
export {};
Sveltejs/kit version - 1.7.2
vite-wa/sveltekit version - 0.2.5
What am I doing wrong ? Any help will be appreciated. thanks.
We're looking at how to avoid breaking downstream dependencies and were thinking about adding an ecosystem CI similar to Vite. In order to do that, we'd need there to be at least one test in this project that we could run to ensure we hadn't broken it
once vite-plugin-pwa released (0.13.0?), remove the local copy and install the new one released
I am using this for a SvelteKit app in SPA mode.
These are the configs:
vite.config.js
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
import { SvelteKitPWA } from '@vite-pwa/sveltekit';
export default defineConfig({
plugins: [
sveltekit(),
SvelteKitPWA({
injectRegister: 'inline',
})
]
});
svelte.config.js
import adapter from '@sveltejs/adapter-static';
import { vitePreprocess } from '@sveltejs/kit/vite';
/** @type {import('@sveltejs/kit').Config} */
export default {
kit: {
adapter: adapter({
fallback: 'index.html',
precompress: !!process.env.CF_PAGES,
})
},
preprocess: vitePreprocess()
};
+layout.js
export const ssr = false;
export const prerender = false; // SPA mode
However, despite all attempts for a full day, the output index.html has no meta tags linking to the manifest and has no script tag or even inline script to do the register / inject. Both inline mode or script doesn't work. Both of them are behaving like null.
Dependencies:
"@sveltejs/kit": "^1.5.0",
"@vite-pwa/sveltekit": "^0.2.2",
"@sveltejs/adapter-static": "^2.0.2",
"vite": "^4.3.0"
"svelte": "^3.54.0",
can't install @vite-pwa/sveltekit
Error message:
ERR_PNPM_FETCH_404 GET https://registry.npmjs.org/@vite-pwa%2Fsveltekit: Not Found - 404
This error happened while installing a direct dependency of C:\Users\Maldita\Documents\Homework\my-app
@vite-pwa/sveltekit is not in the npm registry, or you have no permission to fetch it.
No authorization header was set for the request.
Progress: resolved 2, reused 2, downloaded 0, added 0
how to reproduce
The service worker doesn't register in Firefox browser when injectManifest
mode is on. It fails with an SW registration error TypeError: ServiceWorker script at http://localhost:5173/dev-sw.js?dev-sw for scope http://localhost:5173/ threw an exception during script evaluation.
error.
Any idea why the injectManifest
mode doesn't register properly in Firefox?
I would expect the sample to work out of the box
git clone https://github.com/vite-pwa/sveltekit.git
cd .\sveltekit\examples\sveltekit-ts\
npm install
npm install @vite-pwa/sveltekit -D
npm run build
npm run preview
build warning
PWA v0.14.3
mode injectManifest
precache 41 entries (861.89 KiB)
files generated
.svelte-kit\output\client\prompt-sw.js
warnings
One of the glob patterns doesn't match any files. Please remove or fix the following: {
"globDirectory": ".svelte-kit/output",
"globPattern": "prerendered/**/*.html",
"globIgnores": [
"**/node_modules/**/*",
"client/prompt-sw.js",
"client/prompt-sw.js"
]
}
appears in dev tools
Uncaught non-precached-url: createHandlerBoundToURL('/') was called, but that URL is not precached. Please pass in a URL that is precached instead.
at PrecacheController.createHandlerBoundToURL (http://localhost:4173/prompt-sw.js:1493:13)
at createHandlerBoundToURL (http://localhost:4173/prompt-sw.js:2079:30)
at http://localhost:4173/prompt-sw.js:2176:3
Node : 18.7.0
OS : win32 x64
npm : 8.16.0
A follow up to my (incorrect) bug report in #42, @vite-pwa/sveltekit
does hide legitimate errors coming from Sveltekit's build with its own error.
Basic repro:
vite-pwa/sveltekit
in a projectvite-pwa/sveltekit
(stacktrace in #42) rather than the actual error from sveltekitHey, I am getting the following error:
Uncaught non-precached-url: non-precached-url :: [{"url":"/"}]
I checked the _urlsToCacheKeys, and the base URL is not included.
Prerendering is completely disabled in my project.
The dev mode works fine - the problem only occurs in production mode.
System:
OS: Linux 5.15 Ubuntu 22.04.1 LTS 22.04.1 LTS (Jammy Jellyfish)
CPU: (16) x64 Intel(R) Core(TM) i9-9900KS CPU @ 4.00GHz
Memory: 3.67 GB / 15.54 GB
Container: Yes
Shell: 5.1.16 - /bin/bash
Binaries:
Node: 16.14.0 - ~/.nvm/versions/node/v16.14.0/bin/node
Yarn: 1.22.19 - ~/.yarn/bin/yarn
npm: 8.4.1 - ~/.nvm/versions/node/v16.14.0/bin/npm
Browsers:
Chrome: 107.0.5304.87
npmPackages:
@sveltejs/adapter-node: 1.0.0-next.100 => 1.0.0-next.100
@sveltejs/kit: 1.0.0-next.548 => 1.0.0-next.548
svelte: ^3.53.1 => 3.53.1
vite: ^3.2.4 => 3.2.4
is this line wrong?, review it: https://github.com/userquin/vite-pwa-sveltekit-integration/blob/main/src/index.ts#L15
make a copy of kit entry outside the pwa callback, once provided shouldn't be changed
Following on from here: #52
I ran into more issues, specifically that loading routes from the server other than the home screen (which had been precached) causes issues as they have not been precached. It's not possible for me to precache all routes because some are dynamic.
To be honest, I don't know if this is a problem relating to this package or sveltekit, and in the end I've migrated everything to pure svelte, instead of using sveltekit. But I thought I would just notify you here in case it's of interest to you.
we should also update vite-plugin-pwa
examples
Hello,
I know this issue has already been talked about but I still can't figure out how to fix.
The service worker is registered without any issue in development, in production I get this error :
Uncaught (in promise) non-precached-url: non-precached-url :: [{"url":"/"}]
Here is my config
SvelteKitPWA({
registerType: 'prompt',
base: '/',
scope: '/',
filename: 'sw.js',
mode: 'production',
devOptions: {
enabled: false
},
includeAssets: [
...
],
manifest: {
name: '...',
short_name: '...',
description: '...',
start_url: '/home',
scope: '/',
publicPath: '/',
display: 'standalone',
theme_color: '#ffffff',
icons: [
...
]
}
}),
From what I understand on possibility would be to disable cache completely, I don't know how or if it's possible.
A better solution would be to set up a fallback url, have something that is cache for the "/" route.
Can you help on that ?
Thanks
we should also add gh funding and actions
Hi,
I am able to build the Sveltekit app successfully in my local environment (using podman with image node:18), but when I run the build command from within a Gitlab-CI runner using the same image (node:18) running the exact same commands I get the following error, after building the ssr bundle, when it's building client-side files. It instantly fails with the following error.
vite v4.4.9 building SSR bundle for production...
transforming...
✓ 321 modules transformed.
[vite-plugin-pwa:sveltekit:build] The 'swSrc' file can't be read. ENOENT: no such file or directory,
open '/builds/metier-plus/web/test/admin/.svelte-kit/output/client/service-worker.js'
SvelteKitPWA({
strategies: "injectManifest",
mode: process.env.NODE_ENV,
srcDir: "./src",
filename: "sw.ts",
scope: "/",
base: "/",
// injectRegister: null,
selfDestroying: process.env.SELF_DESTROYING_SW === "true",
manifest: {
name: "App",
short_name: "App",
start_url: "/",
scope: "/",
display: "standalone",
theme_color: "#ffffff",
background_color: "#ffffff",
icons: [
{
src: "/android-chrome-192x192.png",
sizes: "192x192",
type: "image/png",
},
{
src: "/android-chrome-512x512.png",
sizes: "512x512",
type: "image/png",
},
{
src: "/android-chrome-512x512.png",
sizes: "512x512",
type: "image/png",
purpose: "maskable",
},
],
},
injectManifest: {
globPatterns: ["client/**/*.{js,css,ico,png,svg,webp,woff,woff2}"],
maximumFileSizeToCacheInBytes: 10 * 1000 * 1000,
// Tried with & without
injectionPoint: undefined,
},
// Tried with & without
workbox: {
globPatterns: ["client/**/*.{js,css,ico,png,svg,webp,woff,woff2}"],
maximumFileSizeToCacheInBytes: 10 * 1000 * 1000,
injectionPoint: undefined,
},
devOptions: {
enabled: !process.env.SW_DEV,
type: "module",
navigateFallback: "/",
},
}),
It might be a Vite/Sveltekit issue? It seems like Vite/Sveltekit doesn't load the configs for the client-side bundling, so Sveltekit doesn't create the .svelte-kit/output/client
directory & then VitePWA errors for the directory not found?
Hey folks,
After reading the docs over and over, I can't for the life of me figure out why I'm having so much trouble building my project with @vite-pwa/sveltekit
. I based most of my implementation off of this repo, which successfully uses the plugin, yet when I try to build I receive:
warnings
One of the glob patterns doesn't match any files. Please remove or fix the following: {
"globDirectory": "/Users/tjnickerson/Documents/GitHub/Nickersoft/vite-pwa-repro/.svelte-kit/output",
"globPattern": "client/**/*.{js,css,ico,png,svg,webp,webmanifest}",
"globIgnores": [
"**/node_modules/**/*",
"server/sw.js",
"server/workbox-*.js"
]
}
One of the glob patterns doesn't match any files. Please remove or fix the following: {
"globDirectory": "/Users/tjnickerson/Documents/GitHub/Nickersoft/vite-pwa-repro/.svelte-kit/output",
"globPattern": "prerendered/**/*.html",
"globIgnores": [
"**/node_modules/**/*",
"server/sw.js",
"server/workbox-*.js"
]
}
[vite-plugin-pwa:sveltekit:build] ENOENT: no such file or directory, open '/Users/tjnickerson/Documents/GitHub/Nickersoft/vite-pwa-repro/.svelte-kit/output/client/sw.js'
error during build:
Error: ENOENT: no such file or directory, open '/Users/tjnickerson/Documents/GitHub/Nickersoft/vite-pwa-repro/.svelte-kit/output/client/sw.js'
ELIFECYCLE Command failed with exit code 1.
Removing the custom code I have in +layout.svelte
seems to fix the build, even though the code I put in there is verbatim from the docs. The reason the plugin can't find the above file is because sw.js
instead lives in .svelte-kit/server
, not client
.
My reproduction repo is here. You just run pnpm install
and then pnpm build
. Any pointers would be appreciated.
I'm trying to get this package working with a SPA with export const ssr = false;
but it doesn't seem to be working when deployed. It works fine in dev mode.
I get this error
workbox-3625d7b0.js:1 Uncaught (in promise) non-precached-url: non-precached-url :: [{"url":"/"}]
at O.createHandlerBoundToURL (https://test-sveltkit-gfjc7ulcj-hamishjohnson.vercel.app/workbox-3625d7b0.js:1:13245)
at Object.createHandlerBoundToURL (https://test-sveltkit-gfjc7ulcj-hamishjohnson.vercel.app/workbox-3625d7b0.js:1:14916)
at https://test-sveltkit-gfjc7ulcj-hamishjohnson.vercel.app/sw.js:1:3190
And so I tried prerendering the homepage but kept getting further precache issues
Here's an example repo https://github.com/hamishjohnson/test-sveltkit-pwa
And here it is deployed: https://test-sveltkit-gfjc7ulcj-hamishjohnson.vercel.app/ with errors in console
it will require to change pwa plugin api: https://github.com/antfu/vite-plugin-pwa/blob/main/src/html.ts#L22
It will be better to also expose the webmanifest link.
@benmccann is there some dts we can use from kit side here https://github.com/userquin/vite-pwa-sveltekit-integration/blob/main/src/types.ts#L3?
we should check if latest kit changes are ok in the types
First of all, thank you very much for creating this package! I currently trying to use it to create a small PWA hosted via github-pages.
However, this means that the app will served under a subdomain. As per the sveltekit documentation I configured the base path (kit.paths.base
in svelte.config.js
) accordingly.
Unfortunately this seems to break vite-pwa. Looking at the logs, the app still tries to pull the manifest, the sw.js
, and icons from the url root and not the configured base-path.
I could not find any further information about this and I have limited knowledge of creating PWAs. So it might be that I just require an additional setting that I am missing.
I would appreciate any pointer in the right direction :)
I just installed the package with pnpm, followed the docs, added the auto update script and I get this error:
dependencies:
"@vite-pwa/sveltekit": "^0.0.1",
"vite": "^3.2.2",
"vite-plugin-pwa": "^0.13.1"
"@sveltejs/kit": "next",
vite.config.ts:
import type { UserConfig } from "vite";
import { sveltekit } from "@sveltejs/kit/vite";
import { SvelteKitPWA } from "@vite-pwa/sveltekit";
const config: UserConfig = {
plugins: [
sveltekit(),
SvelteKitPWA({
devOptions: {
enabled: true,
},
manifest: {
scope: "/",
name: "...",
short_name: "...",
description: "...",
theme_color: "#ffffff",
icons: [
{
src: "/icons/android-chrome-192x192.png",
sizes: "192x192",
type: "image/png",
},
{
src: "/icons/android-chrome-512x512.png",
sizes: "512x512",
type: "image/png",
},
{
src: "/icons/android-chrome-512x512.png",
sizes: "512x512",
type: "image/png",
purpose: "any maskable",
},
],
},
}),
],
};
Node version: v16.18.1
Browser: Chromium and Firefox
There are 2 deprecated packages present in this project
WARN deprecated rollup-plugin-terser@7.0.2: This package has been deprecated and is no longer maintained. Please use @rollup/plugin-terser
WARN deprecated sourcemap-codec@1.4.8: Please use @jridgewell/sourcemap-codec instead
Line 4824 in 2286b7a
Line 5014 in 2286b7a
IntelliJ ESLint plugin not working, run nr lint-fix
: https://github.com/userquin/vite-pwa-sveltekit-integration/blob/main/src/config.ts#L5
In production, when using export const prerender = true
and generateSW
, SvelteKit's default error page no longer works. Instead, the user is shown the page at /
.
Reproduction:
examples/sveltekit-ts
, update package.json
to use "@vite-pwa/sveltekit": "^0.2.1"
npm i
, npm run build
, and npm run preview
http://localhost:4173/
. This shows +page.svelte
as expected.http://localhost:4173/about
. This shows about/+page.svelte
as expected.http://localhost:4173/oops
. This shows +page.svelte
instead of rendering the default error page.This issue does not occur in development. When running npm run dev
and visiting http://localhost:5173/oops
, it shows the default error page.
I'm using Node v16.19.0 and npm v8.19.3.
My versions:
"@sveltejs/kit": "^1.11.0",
"@vite-pwa/sveltekit": "^0.1.3",
"vite-plugin-pwa": "^0.14.4",
I'm not sure if this is still working. It says it cannot find manifest. I mean, based on the doc, I followed each instruction but when I ran it it seems the PWA is not working. Anyone can help? Thank you.
dependencies:
WARN Issues with peer dependencies found
.
├─┬ @vite-pwa/sveltekit 0.0.1
│ └── ✕ missing peer @types/workbox-build@^5.0.1
└─┬ vite-plugin-pwa 0.13.3
└── ✕ unmet peer vite@^3.1.0: found 4.0.2
Peer dependencies that should be installed:
@types/workbox-build@^5.0.1
I have a config like this:
SvelteKitPWA({
strategies: 'injectManifest',
// // this affect whether workbox output log and the bundle is minified or not
// mode: "development",
mode: "production",
registerType: "prompt",
injectManifest: {
globIgnores: ["server/**", "**/*.{css,js}"],
globPatterns: ["**/*.{ico,jpg,jpeg,png,svg,woff,woff2}"],
},
minify: true,
})
And a simple service worker like this:
/// <reference lib="WebWorker" />
/// <reference types="vite/client" />
/// <reference no-default-lib="true"/>
/// <reference lib="esnext" />
import {
cleanupOutdatedCaches,
createHandlerBoundToURL,
precacheAndRoute,
} from "workbox-precaching";
import { NavigationRoute, registerRoute } from "workbox-routing";
import { CacheFirst, StaleWhileRevalidate } from "workbox-strategies";
import { ExpirationPlugin } from "workbox-expiration";
import type { ManifestEntry } from "workbox-build";
declare let self: ServiceWorkerGlobalScope;
self.addEventListener("message", (event) => {
if (event.data && event.data.type === "SKIP_WAITING") {
self.skipWaiting();
}
});
const manifest = self.__WB_MANIFEST as Array<ManifestEntry>;
precacheAndRoute(manifest);
// clean old assets
cleanupOutdatedCaches();
And I can see the generated sw is not minified, nor replaced process.env.NODE_ENV
. Is it intended for the user to fix themselves with rollup plugins?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.