Skip to content

Commit

Permalink
refactor: use order/handler for transformIndexHtml (#590)
Browse files Browse the repository at this point in the history
  • Loading branch information
sapphi-red authored Nov 4, 2023
1 parent b353ea2 commit 18af770
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 24 deletions.
30 changes: 19 additions & 11 deletions src/plugins/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,30 @@ import { _generateBundle, _generateSW } from '../api'
import type { PWAPluginContext } from '../context'

export function BuildPlugin(ctx: PWAPluginContext) {
const transformIndexHtmlHandler = (html: string) => {
const { options, useImportRegister } = ctx
if (options.disable)
return html

// if virtual register is requested, do not inject.
if (options.injectRegister === 'auto')
options.injectRegister = useImportRegister ? null : 'script'

return injectServiceWorker(html, options, false)
}

return <Plugin>{
name: 'vite-plugin-pwa:build',
enforce: 'post',
apply: 'build',
transformIndexHtml: {
enforce: 'post',
transform(html) {
const { options, useImportRegister } = ctx
if (options.disable)
return html

// if virtual register is requested, do not inject.
if (options.injectRegister === 'auto')
options.injectRegister = useImportRegister ? null : 'script'

return injectServiceWorker(html, options, false)
order: 'post',
handler(html) {
return transformIndexHtmlHandler(html)
},
enforce: 'post', // deprecated since Vite 4
async transform(html) { // deprecated since Vite 4
return transformIndexHtmlHandler(html)
},
},
generateBundle(_, bundle) {
Expand Down
34 changes: 21 additions & 13 deletions src/plugins/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,23 +27,31 @@ export const swDevOptions = {
}

export function DevPlugin(ctx: PWAPluginContext) {
const transformIndexHtmlHandler = (html: string) => {
const { options } = ctx
if (options.disable || !options.manifest || !options.devOptions.enabled)
return html

html = injectServiceWorker(html, options, true)

return html.replace(
'</body>',
`${generateRegisterDevSW(options.base)}
</body>`,
)
}

return <Plugin>{
name: 'vite-plugin-pwa:dev-sw',
apply: 'serve',
transformIndexHtml: {
enforce: 'post',
async transform(html) {
const { options } = ctx
if (options.disable || !options.manifest || !options.devOptions.enabled)
return html

html = injectServiceWorker(html, options, true)

return html.replace(
'</body>',
`${generateRegisterDevSW(options.base)}
</body>`,
)
order: 'post',
async handler(html) {
return transformIndexHtmlHandler(html)
},
enforce: 'post', // deprecated since Vite 4
async transform(html) { // deprecated since Vite 4
return transformIndexHtmlHandler(html)
},
},
configureServer(server) {
Expand Down

0 comments on commit 18af770

Please sign in to comment.