{"id":"50c0eaeca8f6e8e2","repo":"vitest-dev/vitest","slug":"failed-to-load-custom-defines-error-message","errorCode":null,"errorMessage":"Failed to load custom \"defines\": ${error.message}","messagePattern":"Failed to load custom \"defines\": (.+?)","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/vitest/src/runtime/workers/base.ts","lineNumber":99,"sourceCode":"  const startTime = performance.now()\n  const {\n    environment: { name: environmentName, options: environmentOptions },\n    rpc,\n    config,\n  } = context\n\n  setupEnv(config.env, context.metaEnv)\n\n  // we could load @vite/env, but it would take ~8ms, while this takes ~0,02ms\n  if (context.config.serializedDefines) {\n    try {\n      runInThisContext(`(() =>{\\n${context.config.serializedDefines}})()`, {\n        lineOffset: 1,\n        filename: 'virtual:load-defines.js',\n      })\n    }\n    catch (error: any) {\n      throw new Error(`Failed to load custom \"defines\": ${error.message}`)\n    }\n  }\n  const otel = context.traces\n\n  const { environment, loader } = await loadEnvironment(\n    environmentName,\n    config.root,\n    rpc,\n    otel,\n    context.config.experimental.viteModuleRunner,\n  )\n  _currentEnvironment = environment\n  const env = await otel.$(\n    'vitest.runtime.environment.setup',\n    {\n      attributes: {\n        'vitest.environment': environment.name,\n        'vitest.environment.vite_environment': environment.viteEnvironment || environment.name,","sourceCodeStart":81,"sourceCodeEnd":117,"githubUrl":"https://github.com/vitest-dev/vitest/blob/d568f8ce3739b532d5bf2c1ee1e45e8a8a473d09/packages/vitest/src/runtime/workers/base.ts#L81-L117","documentation":"Vitest injects user-defined `define` replacements as serialized JS and evaluates them via node:vm runInThisContext during base environment setup (base.ts:91-100). If that generated code is syntactically invalid or throws at runtime, the original error is wrapped and rethrown with this message naming the define failure.","triggerScenarios":"Configuring test.define (or vite define) with values whose serialized form produces invalid JavaScript, e.g. a define value that is not properly JSON-stringified, a string value inserted without quotes, or a define referencing an undefined variable. Reached when config.serializedDefines is truthy and runInThisContext throws.","commonSituations":"Setting define: { 'import.meta.env.FOO': someVariable } where someVariable is an object/function that serializes to invalid code; passing a raw string without JSON.stringify; a define key/value pair that produces a syntax error when spliced into an IIFE.","solutions":["Use JSON.stringify on define values so they serialize as valid JS literals.","Simplify define to a single key/value and re-add entries to isolate which one produces invalid code.","Check the inner error.message (appended after 'Failed to load custom \"defines\":') for the exact syntax/runtime cause."],"exampleFix":"// before: object value serializes to [object Object]\ndefine: { 'import.meta.env.cfg': { a: 1 } }\n\n// after: stringify the value\ndefine: { 'import.meta.env.cfg': JSON.stringify({ a: 1 }) }","handlingStrategy":"validation","validationCode":"function validateDefines(defines: Record<string, unknown>) {\n  for (const [key, value] of Object.entries(defines)) {\n    const serialized = typeof value === 'string' ? value : JSON.stringify(value)\n    try {\n      // wrap in expression position to mimic vitest's define injection\n      new Function(`return (${serialized})`)\n    } catch (e) {\n      throw new Error(`Invalid define for '${key}': ${(e as Error).message}`)\n    }\n  }\n}","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Always JSON.stringify non-primitive define values in config.","Keep define values static literals (strings, numbers, booleans, JSON).","Add a smoke test that boots Vitest with the define config before running the full suite."],"tags":["define","config","base-pool","vm-eval"],"analyzedSha":"d568f8ce3739b532d5bf2c1ee1e45e8a8a473d09","analyzedAt":"2026-08-03T20:23:56.861Z","schemaVersion":2}