vitest: Vitest cannot transpile with TypeScript `moduleResolution` set to `node16`

Describe the bug

When transpiling a trivial TypeScript library using the TypeScript-recommended module resolution (i.e.: "moduleResolution": "Node16", "module": "Node16"), tsc throws an error on Vitests’ CommonJS version of the type declarations. These declarations in turn incorrectly reference the ES Module version of the declarations, which results in the error.

See https://github.com/softcraft-development/vitest-issue/blob/main/README.md for further details. It references https://www.typescriptlang.org/docs/handbook/modules/guides/choosing-compiler-options.html#im-writing-a-library, which in turn strongly recommends "moduleResolution": "Node16", "module": "Node16" as the tsconfig.json settings for Node libraries, both with and without the use of a bundler.

Correct handling of JavaScript/TypeScript modules is still overly complicated in 2024. In my own libraries I’ve taken to creating entirely separate ESM and CommonJS versions. It looks like Vitest is trying to mix the two strategies, which doesn’t work under every circumstance.

Reproduction

  1. Clone the repository I created to demonstrate this issue: https://github.com/softcraft-development/vitest-issue
  2. Execute npm install to install the dependencies, including TypeScript and Vitest.
  3. Execute npm run node16

This generates the error:

node_modules/vitest/index.d.cts:1:15 - error TS1479: The current file is a CommonJS module whose imports will produce 'require' calls; however, the referenced file is an ECMAScript module and cannot be imported with 'require'. Consider writing a dynamic 'import("./dist/index.js")' call instead.

System Info

System:
    OS: macOS 12.6
    CPU: (8) x64 Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz
    Memory: 19.16 MB / 16.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 18.18.2 - ~/.nvm/versions/node/v18.18.2/bin/node
    npm: 9.8.1 - ~/.nvm/versions/node/v18.18.2/bin/npm
    pnpm: 9.1.4 - ~/Library/pnpm/pnpm
  Browsers:
    Chrome: 125.0.6422.114
    Safari: 16.1
  npmPackages:
    vitest: ^1.6.0 => 1.6.0

Used Package Manager

npm

Validations

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 3
  • Comments: 17 (2 by maintainers)

Commits related to this issue

Most upvoted comments

Why would you compile Vitest tests into CJS?

I’m not; I’m using tsc to do type checking on the test files (along side the source files). Note the noEmit: true setting in tsconfig.json.