Skip to content
Latchkey

Vitest/Jest "import.meta" Undefined - env & glob Not Available in Tests

import.meta is an ESM-only construct. Under Jest’s default CommonJS runtime it is a syntax error, and even under Vitest, import.meta.env values depend on the resolved mode - so tests can see undefined where the app sees a value.

What this error means

A module using import.meta.env.VITE_X or import.meta.glob fails in tests: Jest throws "Cannot use import.meta outside a module," or Vitest reads import.meta.env.VITE_X as undefined even though the dev build has it.

Test output
SyntaxError: Cannot use 'import.meta' outside a module

  > 3 | const base = import.meta.env.VITE_API_URL;
      |                     ^
  (Jest, default CommonJS runtime)

Common causes

Jest CommonJS has no import.meta

Jest transpiles to CommonJS by default, where import.meta does not exist. Code that reads import.meta.env breaks at parse/eval time unless mapped or polyfilled.

Vitest env not loaded for tests

Vitest exposes import.meta.env, but only variables present in the resolved mode/.env are defined. A VITE_-prefixed var missing from the test environment reads as undefined.

How to fix it

In Vitest, provide env values for tests

Define the values Vitest should expose, or set them in a setup file.

vitest.config.ts
// vitest.config.ts
import { defineConfig } from 'vitest/config';
export default defineConfig({
  define: { 'import.meta.env.VITE_API_URL': JSON.stringify('http://localhost') },
  test: { env: { VITE_API_URL: 'http://localhost' } },
});

In Jest, avoid raw import.meta

  1. Read config through a small wrapper (getApiUrl()) you can mock in Jest, instead of import.meta inline.
  2. Or run Jest in native ESM (NODE_OPTIONS=--experimental-vm-modules) with a transform that preserves import.meta.
  3. Provide a Babel plugin to rewrite import.meta.env to process.env for the Jest build.

How to prevent it

  • Centralize env access behind a wrapper so tests can mock it.
  • Define required import.meta.env values in the Vitest config.
  • Prefer Vitest for Vite apps that lean on import.meta.

Frequently asked questions

What causes ""Cannot use import.meta""?
Jest transpiles to CommonJS by default, where import.meta does not exist. Code that reads import.meta.env breaks at parse/eval time unless mapped or polyfilled.
How do I fix "Cannot use import.meta"?
Define the values Vitest should expose, or set them in a setup file.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card