Type process.env in a Node.js or a Vite project
VS Code IntelliSense autocompletion in JavaScript and TypeScript
TL;DR
Install @types/node and create a env.d.ts
file with the following content.
declare namespace NodeJS {
interface ProcessEnv {
// more env variables...
}
}
Top-level declarations in .d.ts files must start with either a ‘declare’ or ‘export’ modifier.
ts(1046)
How it works
By default, VS Code IntelliSense does not know what process.env
is. After all, it might not be a Node.js project. The @types/node type definitions add a global namespace called NodeJS
which includes an ProcessEnv
interface.
By creating a .d.ts
file with the same namespace and interface name, it is possible to extend the ProcessEnv
definition. Now IntelliSense autocompletes both TZ
(which is included in the process.d.ts
) and name
(which is added).
declare namespace NodeJS {
interface ProcessEnv {
// more env variables...
name: 'hyunbin';
}
}
Typing in a Vite project
Vite provides a straight-forward guide. Create a src/env.d.ts
file as shown and add VITE_
prefixed variables in the ImportMetaEnv
interface.
/// <reference types="vite/client" />interface ImportMetaEnv {
readonly VITE_APP_TITLE: string
// more env variables...
}interface ImportMeta {
readonly env: ImportMetaEnv
}
However, the above interface types import.meta.env
, not process.env
. The latter is sometimes needed in a Vite project. One method is to add all variables to ImportMetaEnv
and set the ProcessEnv
to ImportMetaEnv
as the following.
declare namespace NodeJS {
type ProcessEnv = ImportMetaEnv;
}
Or just create two .d.ts
files and separate VITE prefixed and non-prefixed variables. Choose a method that suits the project structure.