DEV Community

rxliuli
rxliuli

Posted on

3 2 1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay