diff --git a/packages/vitest/src/runtime/vm/commonjs-executor.ts b/packages/vitest/src/runtime/vm/commonjs-executor.ts index 42682275b257..d1226d6fa186 100644 --- a/packages/vitest/src/runtime/vm/commonjs-executor.ts +++ b/packages/vitest/src/runtime/vm/commonjs-executor.ts @@ -237,7 +237,8 @@ export class CommonjsExecutor { private requireJs = (m: NodeJS.Module, filename: string) => { const content = this.fs.readFile(filename) - ;(m as PrivateNodeModule)._compile(content, filename) + const code = content.startsWith('#!') ? `//${content.slice(2)}` : content + ;(m as PrivateNodeModule)._compile(code, filename) } private requireJson = (m: NodeJS.Module, filename: string) => { diff --git a/test/e2e/test/vm-threads.test.ts b/test/e2e/test/vm-threads.test.ts index 49eacb0ec71e..cb1e90c94473 100644 --- a/test/e2e/test/vm-threads.test.ts +++ b/test/e2e/test/vm-threads.test.ts @@ -237,6 +237,42 @@ test.for(['vmThreads', 'vmForks'] as const)( }, ) +test.for(['vmThreads', 'vmForks'] as const)( + '%s loads CommonJS dependencies that start with a hashbang', + async (pool) => { + const { stderr, exitCode } = await runInlineTests( + { + 'node_modules/hashbang-cjs/package.json': JSON.stringify({ + name: 'hashbang-cjs', + main: './index.cjs', + }), + 'node_modules/hashbang-cjs/index.cjs': + '#!/usr/bin/env node\nmodule.exports = { value: "cjs" }\n', + 'node_modules/hashbang-js/package.json': JSON.stringify({ + name: 'hashbang-js', + main: './index.js', + }), + 'node_modules/hashbang-js/index.js': + '#!/usr/bin/env node\nmodule.exports = { value: "js" }\n', + 'basic.test.js': ` + import { expect, test } from 'vitest' + import cjs from 'hashbang-cjs' + import js from 'hashbang-js' + + test('hashbang is ignored', () => { + expect(cjs).toEqual({ value: 'cjs' }) + expect(js).toEqual({ value: 'js' }) + }) + `, + }, + { pool }, + ) + + expect(stderr).toBe('') + expect(exitCode).toBe(0) + }, +) + // The module-sync condition was added in Node 22.12/20.19 when require(esm) // was unflagged. The fix uses the _resolveFilename conditions option which // is only available on Node 22.12+. Node 20 is unfixable and reaches EOL