Skip to content

Commit 1a77c6c

Browse files
authored
fix(vm): strip hashbang before compiling CommonJS dependencies (#11731)
1 parent d5d7d2f commit 1a77c6c

2 files changed

Lines changed: 38 additions & 1 deletion

File tree

‎packages/vitest/src/runtime/vm/commonjs-executor.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -237,7 +237,8 @@ export class CommonjsExecutor {
237237

238238
private requireJs = (m: NodeJS.Module, filename: string) => {
239239
const content = this.fs.readFile(filename)
240-
;(m as PrivateNodeModule)._compile(content, filename)
240+
const code = content.startsWith('#!') ? `//${content.slice(2)}` : content
241+
;(m as PrivateNodeModule)._compile(code, filename)
241242
}
242243

243244
private requireJson = (m: NodeJS.Module, filename: string) => {

‎test/e2e/test/vm-threads.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,42 @@ test.for(['vmThreads', 'vmForks'] as const)(
237237
},
238238
)
239239

240+
test.for(['vmThreads', 'vmForks'] as const)(
241+
'%s loads CommonJS dependencies that start with a hashbang',
242+
async (pool) => {
243+
const { stderr, exitCode } = await runInlineTests(
244+
{
245+
'node_modules/hashbang-cjs/package.json': JSON.stringify({
246+
name: 'hashbang-cjs',
247+
main: './index.cjs',
248+
}),
249+
'node_modules/hashbang-cjs/index.cjs':
250+
'#!/usr/bin/env node\nmodule.exports = { value: "cjs" }\n',
251+
'node_modules/hashbang-js/package.json': JSON.stringify({
252+
name: 'hashbang-js',
253+
main: './index.js',
254+
}),
255+
'node_modules/hashbang-js/index.js':
256+
'#!/usr/bin/env node\nmodule.exports = { value: "js" }\n',
257+
'basic.test.js': `
258+
import { expect, test } from 'vitest'
259+
import cjs from 'hashbang-cjs'
260+
import js from 'hashbang-js'
261+
262+
test('hashbang is ignored', () => {
263+
expect(cjs).toEqual({ value: 'cjs' })
264+
expect(js).toEqual({ value: 'js' })
265+
})
266+
`,
267+
},
268+
{ pool },
269+
)
270+
271+
expect(stderr).toBe('')
272+
expect(exitCode).toBe(0)
273+
},
274+
)
275+
240276
// The module-sync condition was added in Node 22.12/20.19 when require(esm)
241277
// was unflagged. The fix uses the _resolveFilename conditions option which
242278
// is only available on Node 22.12+. Node 20 is unfixable and reaches EOL

0 commit comments

Comments
 (0)