{"record":{"id":"6101cb9fa1218e77","repo":"vitest-dev/vitest","slug":"require-is-not-supported-in-virtual-modules-try","errorCode":null,"errorMessage":"require() is not supported in virtual modules. Trying to call require(\"${id}\") in ${url}","messagePattern":"require\\(\\) is not supported in virtual modules\\. Trying to call require\\(\"(.+?)\"\\) in (.+?)","errorType":"exception","errorClass":"SyntaxError","httpStatus":null,"severity":"error","filePath":"packages/vitest/src/runtime/moduleRunner/moduleEvaluator.ts","lineNumber":450,"sourceCode":"      await initModule(...argumentsValues)\n    }\n    catch (error: unknown) {\n      if (!injectCjsGlobals) {\n        throw enhanceMissingCjsGlobalsError(error)\n      }\n      throw error\n    }\n    finally {\n      // moduleExecutionInfo needs to use Node filename instead of the normalized one\n      // because we rely on this behaviour in coverage-v8, for example\n      this.options.moduleExecutionInfo?.set(options.filename, finishModuleExecutionInfo())\n    }\n  }\n\n  private createRequire(url: string) {\n    if (url.startsWith('data:')) {\n      const _require = (id: string) => {\n        throw new SyntaxError(`require() is not supported in virtual modules. Trying to call require(\"${id}\") in ${url}`)\n      }\n      _require.resolve = _require\n      return _require\n    }\n    return this.vm\n      ? this.vm.externalModulesExecutor.createRequire(url)\n      : createRequire(url)\n  }\n\n  private shouldInterop(path: string, mod: any): boolean {\n    if (this.options.interopDefault === false) {\n      return false\n    }\n    // never interop ESM modules\n    // TODO: should also skip for `.js` with `type=\"module\"`\n    return !path.endsWith('.mjs') && 'default' in mod\n  }\n}","sourceCodeStart":432,"sourceCodeEnd":468,"githubUrl":"https://github.com/vitest-dev/vitest/blob/1fa9837ec26533512fdcad8baebf249771bd340a/packages/vitest/src/runtime/moduleRunner/moduleEvaluator.ts#L432-L468","documentation":"When Vitest evaluates a virtual module whose URL is a `data:` URL, it synthesizes a `require` function that unconditionally throws this `SyntaxError` if called. Virtual modules are ESM-only in Vitest's module runner; CommonJS `require()` has no meaningful resolution target inside a data URL.","triggerScenarios":"Code inside a virtual/inlined module (transformed into a `data:` URL by Vite, e.g. virtual plugin modules like `virtual:...` that get inlined) contains a literal `require('something')` call. The `createRequire` method at moduleEvaluator.ts:447-454 checks `url.startsWith('data:')` and returns the throwing stub.","commonSituations":"A dependency authored as CommonJS that gets inlined/virtualized by a plugin; user code that calls `require()` in an ESM-first Vitest context; a Vite virtual module plugin whose generated code uses `require`; modules that feature-detect `typeof require !== 'undefined'` and then call it.","solutions":["Replace `require(...)` with `import` (static or dynamic `await import(...)`) in the source module.","If the code is in a dependency, check for an ESM build or use `vi.mock`/aliasing to provide an ESM version.","For feature detection, guard the call: `if (typeof require === 'function' && !require.toString().includes('not supported'))` — or simply avoid calling `require` in module-runner-evaluated code.","Ensure the module is loaded as a real file URL (`file://`) rather than inlined as `data:` — check Vite's `optimizeDeps` and plugin `transform` outputs."],"exampleFix":"// before - inside a virtual module\nconst fs = require('fs')\n\n// after\nimport fs from 'node:fs'\n// or\nconst fs = await import('node:fs')","handlingStrategy":"try-catch","validationCode":"if (url.startsWith('data:') && /\\brequire\\s*\\(/.test(sourceCode)) throw new Error('virtual module uses require — convert to import')","typeGuard":"null","tryCatchPattern":"try { await runner.import(virtualId) } catch (e) { if (/require\\(\\) is not supported in virtual modules/.test(e.message)) { convertRequireToImport(virtualId); await runner.import(virtualId) } else throw e }","preventionTips":["Author virtual-module plugin output as pure ESM (use `import`).","Avoid `typeof require` feature-detection that falls through to a `require()` call.","Prefer `createRequire(import.meta.url)` only in real `file://` modules, never in `data:` URLs."],"tags":["virtual-modules","esm","cjs","require","module-runner"],"backgroundTag":null,"analyzedSha":"1fa9837ec26533512fdcad8baebf249771bd340a","analyzedAt":"2026-08-11T16:11:39.638Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}