Skip to content

Allow running Vitest without any transforms #9181

@sheremet-va

Description

@sheremet-va

Clear and concise description of the problem

A lot of projects that do not use Vite and/or are already compiled have to be processed again by the Vite pipeline which can introduce unexpected behaviours that do not exist in the target environment. For example, when you run tests in Vitest, but your production code only in Node, you have access to this values that don't exist in production:

  • import.meta.env
  • __dirname/__filename/exports/module (normally, not available in ESM)

The code also runs via a Module Runner - a concept native to Vite, but foreign to Node ESM. This makes imports more forgiving in your tests which Vitest is famous for - "it just works".

Suggested solution

It would be nice to have a flag to use a native import instead of the Module Runner. This will alleviate all mentioned concerns because the runtime will be the same as the native one (Node/bun/Deno).

There should still be a way to opt-in into native module loader mechanism (Node supports module.registerHooks, bun supports loader hooks).

This preload mechanism should run once during worker initialisation. An example of configuration:

import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    experimental: {
      // preload once when the worker spawns
      workerPreload: ['tsx/loader'], // for Node versions that don't support ts
      // ignore all plugins, including aliases
      ignorePlugins: true,
    },
  },
})

Alternative

No response

Additional context

Some features of Vitest rely on plugins, so we need to make a decision if they should run anyway (using module.registerHooks, for example - not sure what to do with Deno/bun in this case). Disabling them makes it hard and confusing to document.

  • no import.meta.env in Node: import.meta.env is a Vite feature, use process.env instead
  • no import.meta.vitest: in-source testing requires injecting values to import.meta which is not supported by any environment (except via transformation)
  • no vi.mock support: mocking modules is not supported because it relies on code transformations
  • no alias: aliases are not applied because there is no transformation/resolution phase

Some of the features requires some kind of transform mechanism, e.g. watch mode, so we will have to do some kind of transformation at least.

There is already a partial implementation of this feature at #7234

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    p2-nice-to-haveNot breaking anything but nice to have (priority)

    Projects

    Status

    P2 - 5

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions