diff --git a/packages/playground/html/__tests__/html.spec.ts b/packages/playground/html/__tests__/html.spec.ts index ce0f640d8acbb7..a129fd6ed3b07f 100644 --- a/packages/playground/html/__tests__/html.spec.ts +++ b/packages/playground/html/__tests__/html.spec.ts @@ -104,6 +104,7 @@ if (isBuild) { test('script is async', async () => { expect(await page.$('head script[type=module][async]')).toBeTruthy() + expect(await page.$('head script[type=module]:not([async])')).toBeNull() }) }) @@ -115,6 +116,20 @@ if (isBuild) { test('script is mixed', async () => { expect(await page.$('head script[type=module][async]')).toBeNull() + expect(await page.$('head script[type=module]:not([async])')).toBeTruthy() + }) + }) + + describe('zeroJS', () => { + // Ensure that the modulePreload polyfill is discarded in this case + + beforeAll(async () => { + // viteTestUrl is globally injected in scripts/jestPerTestSetup.ts + await page.goto(viteTestUrl + '/zeroJS.html') + }) + + test('zeroJS', async () => { + expect(await page.$('head script[type=module]')).toBeNull() }) }) diff --git a/packages/playground/html/vite.config.js b/packages/playground/html/vite.config.js index d538bf4b365d32..36d248e954921e 100644 --- a/packages/playground/html/vite.config.js +++ b/packages/playground/html/vite.config.js @@ -11,6 +11,7 @@ module.exports = { nested: resolve(__dirname, 'nested/index.html'), scriptAsync: resolve(__dirname, 'scriptAsync.html'), scriptMixed: resolve(__dirname, 'scriptMixed.html'), + zeroJS: resolve(__dirname, 'zeroJS.html'), inline1: resolve(__dirname, 'inline/shared-1.html'), inline2: resolve(__dirname, 'inline/shared-2.html'), inline3: resolve(__dirname, 'inline/unique.html') diff --git a/packages/playground/html/zeroJS.html b/packages/playground/html/zeroJS.html new file mode 100644 index 00000000000000..b67e71dd200ff1 --- /dev/null +++ b/packages/playground/html/zeroJS.html @@ -0,0 +1,9 @@ + + +

zeroJS.html

+ + diff --git a/packages/vite/src/node/plugins/html.ts b/packages/vite/src/node/plugins/html.ts index 9ec7282340e51e..68df608d0f69ee 100644 --- a/packages/vite/src/node/plugins/html.ts +++ b/packages/vite/src/node/plugins/html.ts @@ -293,8 +293,11 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { processedHtml.set(id, s.toString()) - // inject module preload polyfill - if (config.build.polyfillModulePreload) { + // inject module preload polyfill only when configured and needed + if ( + config.build.polyfillModulePreload && + (someScriptsAreAsync || someScriptsAreDefer) + ) { js = `import "${modulePreloadPolyfillId}";\n${js}` } @@ -391,6 +394,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { chunk.isEntry && chunk.facadeModuleId === id ) as OutputChunk | undefined + let canInlineEntry = false // inject chunk asset links