Skip to content

Vitest incorrectly injects __dirname when type is module #2841

@snyamathi

Description

@snyamathi

Describe the bug

I'm in the process of migrating a large codebase from CJS to ESM. One of the main "gotchas" is
that there is No __filename or __dirname.

I'm getting a lot of tests which incorrectly pass when they should actually fail because Vitest seems to inject the __dirname into the ES Module. This would be fine for CommonJS but is not correct for ESM.

Please see the minimal example enclosed where npx vitest run will pass, but node index.js will fail.

It actually looks like all of the CJS Module Scope is available in ESM. This is not correct and will cause a lot of issues for developers who want to accurately test against an ESM environment.

Screenshot 2023-02-08 at 10 48 12 AM

Reproduction

https://stackblitz.com/edit/vitest-dev-vitest-ixfqyt?file=index.js

$ cat index.js
export default __dirname;

$ jq '.type' package.json 
"module"

$ npx vitest run
 RUN  v0.28.4 /home/projects/vitest-dev-vitest-ixfqyt

 ✓ index.test.js (1)

 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  09:37:40
   Duration  4.72s (transform 136ms, setup 0ms, collect 21ms, tests 3ms)

$ node index.js
Error: __dirname is not defined
    at file:///home/projects/vitest-dev-vitest-ixfqyt/index.js
    at async ESMLoader.import (https://vitestdevvitestixfqyt-psy2.w-credentialless.staticblitz.com/blitz.2913a9f2fedb71678a44d5a6b5e0b08a6f00d17f.js:6:1209048)
    at async i.loadESM (https://vitestdevvitestixfqyt-psy2.w-credentialless.staticblitz.com/blitz.2913a9f2fedb71678a44d5a6b5e0b08a6f00d17f.js:6:246622)
    at async handleMainPromise (https://vitestdevvitestixfqyt-psy2.w-credentialless.staticblitz.com/blitz.2913a9f2fedb71678a44d5a6b5e0b08a6f00d17f.js:6:989055)

System Info

System:
    OS: Linux 5.0 undefined
    CPU: (8) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 0 Bytes / 0 Bytes
    Shell: 1.0 - /bin/jsh
  Binaries:
    Node: 16.14.2 - /usr/local/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 7.17.0 - /usr/local/bin/npm
  npmPackages:
    vitest: * => 0.28.4

Used Package Manager

npm

Validations

Metadata

Metadata

Assignees

Labels

p3-minor-bugAn edge case that only affects very specific usage (priority)

Type

No type

Projects

Status

Approved

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions