{"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":436,"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":418,"sourceCodeEnd":454,"githubUrl":"https://github.com/vitest-dev/vitest/blob/d568f8ce3739b532d5bf2c1ee1e45e8a8a473d09/packages/vitest/src/runtime/moduleRunner/moduleEvaluator.ts#L418-L454","documentation":"`VitestModuleEvaluator.createRequire` (`moduleEvaluator.ts:436`) returns a throwing stub for modules whose URL begins with `data:` — these are virtual modules synthesized inline (e.g. automock/manual-generated source has no filesystem path). Node's `require` cannot resolve anything from a `data:` URL, so any `require()` call inside such a module throws this `SyntaxError` naming the required id and the calling url.","triggerScenarios":"An automocked or manually-mocked module (generated `data:` source) that contains a `require()` call; a virtual/Vite-synthesized module using `require`.","commonSituations":"Automocking a CJS-leaning module that calls `require('...')` internally; a manual mock factory whose generated wrapper references `require`; inlining a CJS dependency.","solutions":["Rewrite the module to use ESM `import` instead of `require`.","If you control the mocked code, replace `require` with `createRequire`-free ESM imports or `import.meta`.","Provide a manual mock factory (`vi.mock('mod', () => ({...}))`) that doesn't surface `require` to the evaluator."],"exampleFix":"// before (module being mocked)\nconst fs = require('node:fs')\n\n// after\nimport * as fs from 'node:fs'","handlingStrategy":"validation","validationCode":"// Ensure mocked modules don't use require. Scan before mocking if you\n// control the source; otherwise provide a manual factory.\nfunction usesRequire(source: string): boolean {\n  return /\\brequire\\s*\\(/.test(source)\n}","typeGuard":null,"tryCatchPattern":"try {\n  vi.mock('mod') // automock\n} catch (e) {\n  if (e instanceof SyntaxError && /require\\(\\) is not supported in virtual modules/.test(e.message)) {\n    // provide a manual factory without require\n    vi.mock('mod', () => ({ /* ... */ }))\n  } else throw e\n}","preventionTips":["Avoid require() inside modules that will be automocked — use ESM import.","For CJS deps, provide a manual vi.mock factory instead of relying on automock.","Convert heavily-CJS modules to ESM or externalize them."],"tags":["mocking","virtual-module","commonjs","require","esm","syntaxerror"],"analyzedSha":"d568f8ce3739b532d5bf2c1ee1e45e8a8a473d09","analyzedAt":"2026-08-03T20:23:56.861Z","schemaVersion":2}