DEV Community

rxliuli
rxliuli

Posted on

vite automatically generates type definitions for environment variables

When developing front-end web projects, we often need to use environment variables, and vite, as a very popular build tool recently, supports .env environment variable configuration files, and also supports the type of configuration environment variables. in src/env.d.ts just create the interface ImportMetaEnv. The only bit of trouble: it's not automatic, but requires developers to manually add environment variables. -- This is why this plugin was created, it scans the environment variable configuration and automatically generates the interface ImportMetaEnv if it doesn't exist, or adds the missing environment variable field in the existing interface.

design

Image description

use

pnpm i -D @liuli-util/vite-plugin-env-dts-gen
Enter fullscreen mode Exit fullscreen mode

Configure the plugin

//vite.config.ts
import { defineConfig } from 'vite'
import { envDtsGen } from '@liuli-util/vite-plugin-env-dts-gen'

export default defineConfig({
  plugins: [envDtsGen()],
})
Enter fullscreen mode Exit fullscreen mode

Example

FAQ

The default plugin has the following behavior

  • When the ImportMetaEnv interface in src/vite-env.d.ts already contains fields, it will not be repeatedly added or replaced, but skipped. This behavior is mainly to allow users to customize environment variables
  • never automatically clear an environment variable, even if it no longer exists in .env*, for the same reason as above
  • Forcibly generate an environment variable during build, even if there is no change, this behavior is to avoid building immediately after pulling the code for the first time

Top comments (0)