From 856d3a02dc9cd7974a12cc4ddd2356fab74497b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joaqu=C3=ADn=20S=C3=A1nchez?= Date: Fri, 29 Nov 2024 18:09:21 +0100 Subject: [PATCH] feat(html): add head when missing from entry point (#784) * feat(html): add head when missing from entry point * chore: add warning when missing close head tag in the html --- src/html.ts | 28 ++++++++++++++++++++++++++-- src/pwa-assets/html.ts | 5 +++-- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/src/html.ts b/src/html.ts index 6c5f044e..4b71c93c 100644 --- a/src/html.ts +++ b/src/html.ts @@ -1,3 +1,4 @@ +import { yellow } from 'kolorist' import { DEV_PWA_ASSETS_NAME, DEV_READY_NAME, @@ -25,20 +26,43 @@ navigator.serviceWorker.register('${path}', { scope: '${options.scope}' }) }`.replace(/\n/g, '') } +export function checkForHtmlHead(html: string) { + if (!html.includes('')) { + if (!html.includes('')) { + console.warn([ + '', + yellow('PWA WARNING:'), + ' and tags not found in the html, the service worker and web manifest will not be injected.', + ].join('\n')) + return html + } + else { + console.warn([ + '', + yellow('PWA WARNING:'), + ' not found in the html, adding it to the html tag: add empty to your html to remove this warning.', + ].join('\n')) + } + return html.replace('', `\n\n`) + } + + return html +} + export function injectServiceWorker(html: string, options: ResolvedVitePWAOptions, dev: boolean) { const manifest = generateWebManifest(options, dev) if (!dev) { const script = generateRegisterSW(options, dev) if (script) { - return html.replace( + return checkForHtmlHead(html).replace( '', `${manifest}${script}`, ) } } - return html.replace( + return checkForHtmlHead(html).replace( '', `${manifest}`, ) diff --git a/src/pwa-assets/html.ts b/src/pwa-assets/html.ts index b4251b0d..0d5069b3 100644 --- a/src/pwa-assets/html.ts +++ b/src/pwa-assets/html.ts @@ -1,5 +1,6 @@ import { generateHtmlMarkup } from '@vite-pwa/assets-generator/api/generate-html-markup' import type { PWAPluginContext } from '../context' +import { checkForHtmlHead } from '../html' import type { AssetsGeneratorContext, PWAHtmlAssets } from './types' import { mapLink } from './utils' @@ -11,7 +12,7 @@ export function transformIndexHtml( if (assetsGeneratorContext.injectThemeColor) { const manifest = ctx.options.manifest if (manifest && 'theme_color' in manifest && manifest.theme_color) { - html = html.replace( + html = checkForHtmlHead(html).replace( '', `\n`, ) @@ -21,7 +22,7 @@ export function transformIndexHtml( if (assetsGeneratorContext.includeHtmlHeadLinks) { const link = generateHtmlMarkup(assetsGeneratorContext.assetsInstructions) if (link.length) - html = html.replace('', `\n${link.join('\n')}`) + html = checkForHtmlHead(html).replace('', `\n${link.join('\n')}`) } return html