From 7c3b21f21b521c4c8f83600590199fe4e41f5efd Mon Sep 17 00:00:00 2001 From: shulaoda <165626830+shulaoda@users.noreply.github.com> Date: Fri, 19 Jun 2026 19:39:32 +0800 Subject: [PATCH] fix(css): inject inlined CSS after the shebang line --- .../src/node/__tests__/plugins/css.spec.ts | 25 +++++++++++++++++++ packages/vite/src/node/plugins/css.ts | 11 +++++--- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/packages/vite/src/node/__tests__/plugins/css.spec.ts b/packages/vite/src/node/__tests__/plugins/css.spec.ts index d925ee96a45dc8..231a934eca425f 100644 --- a/packages/vite/src/node/__tests__/plugins/css.spec.ts +++ b/packages/vite/src/node/__tests__/plugins/css.spec.ts @@ -829,4 +829,29 @@ exports.foo = foo; })();" `) }) + + test('should inject CSS after the shebang line for es', async () => { + const result = getInlinedCSSInjectedCode( + `#!/usr/bin/env node +console.log("foo");`, + 'es', + ) + expect(result).toMatchInlineSnapshot(` + "#!/usr/bin/env node + injectCSS();console.log("foo");" + `) + }) + + test('should inject CSS at the start for es without shebang', async () => { + const result = getInlinedCSSInjectedCode(`console.log("foo");`, 'es') + expect(result).toMatchInlineSnapshot(`"injectCSS();console.log("foo");"`) + }) + + test('should inject CSS for es shebang without trailing newline', async () => { + const result = getInlinedCSSInjectedCode(`#!/usr/bin/env node`, 'es') + expect(result).toMatchInlineSnapshot(` + "#!/usr/bin/env node + injectCSS();" + `) + }) }) diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 3669462c422d53..72ca6fa40a8990 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -1159,11 +1159,14 @@ export function injectInlinedCSS( } else if (format === 'es') { // legacy build if (code.startsWith('#!')) { - let secondLinePos = code.indexOf('\n') - if (secondLinePos === -1) { - secondLinePos = 0 + // inject after the shebang line instead of into it + const newlinePos = code.indexOf('\n') + if (newlinePos === -1) { + // the shebang has no trailing newline, add one so it stays intact + s.append(`\n${injectCode}`) + return } - injectionPoint = secondLinePos + injectionPoint = newlinePos + 1 } else { injectionPoint = 0 }