Skip to content

Commit 8cac935

Browse files
authored
fix: handle Vite's base properly in dev server (#657)
1 parent 801e9c4 commit 8cac935

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

src/plugins/dev.ts

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -81,11 +81,11 @@ export function DevPlugin(ctx: PWAPluginContext) {
8181

8282
const { options } = ctx
8383
if (!options.disable && options.devOptions.enabled && options.strategies === 'injectManifest' && !options.selfDestroying) {
84-
const name = id.startsWith('/') ? id.slice(1) : id
85-
// the sw must be registered with .js extension on browser, here we detect that request:
84+
const name = id.startsWith(options.base) ? id.slice(options.base.length) : id
85+
// the sw must be registered with .js extension in the browser, here we detect that request:
8686
// - the .js file and source with .ts, or
8787
// - the .ts source file
88-
// in both cases we need to resolve the id to the source file to load it and add empty injection point on loadDev
88+
// in any case, we need to resolve the id to the source file to load it and add empty injection point on loadDev
8989
// we need to always return the path to source file name to resolve imports on the sw
9090
return (name === swDevOptions.swUrl || name === options.injectManifest.swSrc)
9191
? options.injectManifest.swSrc
@@ -193,6 +193,14 @@ export function DevPlugin(ctx: PWAPluginContext) {
193193
if (swDevOptions.workboxPaths.has(key))
194194
return await fs.readFile(swDevOptions.workboxPaths.get(key)!, 'utf-8')
195195
}
196+
else if (options.base !== '/') {
197+
// Vite will remove the base from the request, so we need to add it back and check if present.
198+
// An example is using /test/registerSW.js, the request will be /registerSW.js.
199+
// So we can handle that request in the middleware or just check it here.
200+
const key = normalizePath(`${options.base}${id.length > 0 && id[0] === '/' ? id.slice(1) : id}`)
201+
if (swDevOptions.workboxPaths.has(key))
202+
return await fs.readFile(swDevOptions.workboxPaths.get(key)!, 'utf-8')
203+
}
196204
}
197205
},
198206
}

0 commit comments

Comments
 (0)