vite-plugin-meta-env

a vite plugin, define dynamic env variables in import.meta.env
28,214 8
Install
npm install vite-plugin-meta-env
Latest Version:1.0.2
License:ISC
Last Updated:Sep 11, 2023
Links: GitHub  ·  npm
Maintainer: wei-zone

vite-plugin-meta-env

English | 简体中文

commitizen Wei Design

define dynamic env variables in import.meta.env

1、Intro

This plugin is used in vite , Expose dynamic or without prefix environment variables in the project

Usage

  • a、dynamicenvironment variables

  • b、without prefixenvironment variables


In vite projects, the environment variable is usually exposed which is starting with envPrefix The default is VITE_,

such as: VITE_API_URL, VITE_APP_NAME and so on.

But sometimes you need to use some dynamic environment variables and variables without prefix such as: APP_VERSION, APP_BUILD_TIME and so on.

This plugin is born to solve this problem.

Here we use the config and define configuration options unique to vite to complete this function

2、Usage

Install

pnpm add vite-plugin-meta-env -D

Config

VitePluginMetaEnv receives two parameters:

/**
 * Use the define option to expose a variable without a prefix
 * @param {EnvVars} Vars environment variable object
 * @param defineOn Variable Definition Location
 */
  • The first parameter: environment variable object, key is the variable name, value is the variable value.
  • The second parameter: variable definition location, optional import.meta.env or process.env
// vite.config.js

import { defineConfig } from 'vite'

// import plugin
import VitePluginMetaEnv from 'vite-plugin-meta-env'

export default () => {
    // environment variables, object structure
    const metaEnv = {
        APP_VERSION: '1.0.0'
    }
    return defineConfig({
        // ...
        plugins: [
            // use plugin
            VitePluginMetaEnv(metaEnv, 'import.meta.env'),
            // VitePluginMetaEnv(metaEnv, 'process.env'),
        ]
    })
}

in the project, you can access the environment variables we defined through import.meta.env.APP_VERSION

demo

preview

3、warning

TypeScript tips

to ensure type checking and code hints, please add type declarations in env.d.ts or vite-env.d.ts

// env.d.ts
/// <reference types="vite/client" />
interface ImportMetaEnv {
    readonly BASE_URL: string // Built-in variable
    readonly MODE: string // Built-in variable
    readonly APP_VERSION: string
    // more...
}

interface ImportMeta {
    readonly env: ImportMetaEnv
}

author

Related Packages

vite-plugin-vue-meta-layouts

vite 的 vue-router 的元信息布局系统

314,627 65
vite-plugin-vue-docgen

A simple vue-docgen plugin for Vite

91,834 8
vite-plugin-favicons-inject

A Vite plugin for creating and injecting favicons during the application build!

533,525 10
vite-plugin-use-modules

自动加载 modules

8,078 14
@vunojs/vite

Vite integration and file-based routing for Vuno.

887

Version History

Version Released License
1.0.2 ISC
1.0.1 ISC
1.0.0 ISC
0.2.0 ISC
0.1.0 ISC