Skip to content

Commit df5a30d

Browse files
authored
fix(config): handle shebang properly (#21158)
1 parent aad075d commit df5a30d

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

packages/vite/src/node/__tests__/config.spec.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -854,6 +854,17 @@ describe('loadConfigFromFile', () => {
854854
expect(c.resolved).toBe(c.url)
855855
})
856856

857+
test('shebang is preserved at the top of the file', async () => {
858+
const { config } = (await loadConfigFromFile(
859+
{} as any,
860+
path.resolve(fixtures, './shebang/vite.config.ts'),
861+
path.resolve(fixtures, './shebang'),
862+
))!
863+
864+
const c = config as any
865+
expect(c.dirname).toContain('shebang')
866+
})
867+
857868
describe('loadConfigFromFile with configLoader: native', () => {
858869
const fixtureRoot = path.resolve(fixtures, './native-import')
859870

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
#!/usr/bin/env node
2+
export default {
3+
dirname: import.meta.dirname,
4+
}

packages/vite/src/node/config.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2044,9 +2044,22 @@ async function bundleConfigFile(
20442044
}
20452045
}
20462046

2047+
let injectedContents: string
2048+
if (contents.startsWith('#!')) {
2049+
// hashbang
2050+
let firstLineEndIndex = contents.indexOf('\n')
2051+
if (firstLineEndIndex < 0) firstLineEndIndex = contents.length
2052+
injectedContents =
2053+
contents.slice(0, firstLineEndIndex + 1) +
2054+
injectValues +
2055+
contents.slice(firstLineEndIndex + 1)
2056+
} else {
2057+
injectedContents = injectValues + contents
2058+
}
2059+
20472060
return {
20482061
loader: args.path.endsWith('ts') ? 'ts' : 'js',
2049-
contents: injectValues + contents,
2062+
contents: injectedContents,
20502063
}
20512064
})
20522065
},

0 commit comments

Comments
 (0)