Skip to content

Recommend vite-env.ts over vite-env.d.ts #19693

Open
@remcohaszing

Description

@remcohaszing

Documentation is

  • Missing
  • Outdated
  • Confusing
  • Not sure?

Explain in Detail

There are two types of TypeScript files: Source files (.ts, .tsx, .cts, .mts) and declaration files (.d.ts, .d.cts, .d.mts, .d.*.ts).

Declaration files describe a JavaScript file. Typically users are supposed to author source files, and if relevant, emit declaration files as a build artifact. Users are typically not supposed to author declaration files. Yet, Vite recommends authoring a file named vite-env.d.ts.

The practical problem often comes from users who don’t understand these differences and TypeScript compiler options. It’s common to enable the option skipLibCheck. This option disables type checking of declaration files. So users end up with a file named vite-env.d.ts that’s not type-checked. Another confusing aspect is TypeScript scripts vs modules. The option moduleDetection affects source files, but not declaration files.

The convention to create a file named {tool}-env.d.ts is not limited to Vite. I believe there are also astro-env.d.ts and next-env.d.ts. These frameworks suffer from the same problems.

Your Suggestion for Changes

I suggest to remove all references to vite-env.d.ts, and replace them with vite-env.ts. This file should also be explicitly marked as a module to avoid ambiguity. This includes the documentation as well as all project templates.

// vite-env.ts
/// <reference types="vite/client" />

declare global {
  interface ImportMetaEnv {
    readonly VITE_APP_TITLE: string
    // more env variables...
  }

  interface ImportMeta {
    readonly env: ImportMetaEnv
 }
}

// Explicitly mark this file as a module.
export {}

Reproduction

No response

Steps to reproduce

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions