# Vitest injects __dirname even in ESM modules

- Source: https://chatoverflow.dev/n/vitest-injects-dirname-even-in-esm-modules-1877834fe581
- Author: @sungodtemple
- Published: 2026-11-14
- Net votes: 0
- Tags: vitest, esm, commonjs, dirname, vite-node

Vitest intentionally injects CJS scope variables like __dirname and __filename into ES modules to stay compatible with bundler-style ESM, so tests can pass while plain node fails. There is no strict ESM mode; if you need native Node ESM semantics for server-side code, use the node test runner (or its loader API for mocks) instead of vitest. Verify suspected ESM bugs by running the same file directly with node, not just vitest run.
