Vite environment variables

Environment variables and patterns

environment variable

Vite exposes environment variables on a special import.meta.env object. Here are some built-in variables that can be used in all cases:

import.meta.env.MODE: {string} 应用运行的模式。

import.meta.env.BASE_URL: {string} 部署应用时的基本 URL。他由base 配置项决定。

import.meta.env.PROD: {boolean} 应用是否运行在生产环境。

import.meta.env.DEV: {boolean} 应用是否运行在开发环境 (永远与 import.meta.env.PROD相反)。

import.meta.env.SSR: {boolean} 应用是否运行在 server 上。

Production environment replacement

In production, these environment variables are statically replaced at build time, so use fully static strings when referencing them. Dynamic keys will not take effect. For example, the dynamic key value import.meta.env[key] is invalid.

It will also replace strings that occur in JavaScript and Vue templates. This should be very rare, but it could have been done accidentally. In this case you may see errors like Missing Semicolon or Unexpected token, for example when "process.env.NODE_ENV" replaced with ""development": ". There are some ways to avoid this problem:

For JavaScript strings, you can use unicode zero-width spaces to split the string, for example: 'import.meta\u200b.env.MODE'.

For Vue templates or other HTML compiled to JavaScript strings, you can use the tag, eg: import.meta.env.MODE .

.env files
Vite uses dotenv to load additional environment variables from the following files in your environment directory:

.env                # 所有情况下都会加载
.env.local          # 所有情况下都会加载,但会被 git 忽略
.env.[mode]         # 只在指定模式下加载
.env.[mode].local   # 只在指定模式下加载,但会被 git 忽略\

Environment loading priority

A file that specifies a schema (eg. .env.production) takes precedence over a generic form (eg. .env).

In addition, the environment variables that already exist when Vite is executed have the highest priority and will not be overwritten by the .env class file. For example when running VITE_SOME_KEY=123 vite build.

The .env class file will be loaded at the beginning of Vite startup, and the changes will take effect after restarting the server.

The loaded environment variables are also exposed to the client source code as strings through import.meta.env.

为了防止意外地将一些环境变量泄漏到客户端,只有以 VITE_ 为前缀的变量才会暴露给经过 vite 处理的代码`. For example, the following environment variables:

VITE_SOME_KEY=123
DB_PASSWORD=foobar
只有 VITE_SOME_KEY 会被暴露为 import.meta.env.VITE_SOME_KEY 提供给客户端源码,而 DB_PASSWORD 则不会。
console.log(import.meta.env.VITE_SOME_KEY) // 123
console.log(import.meta.env.DB_PASSWORD) // undefined
此外,Vite 使用 dotenv-expand 来直接拓展变量。想要了解更多相关语法,请查看 它们的文档。

Note that if you want to use the $ symbol in an environment variable, you must escape it with \.

KEY=123
NEW_KEY1=test$foo   # test
NEW_KEY2=test\$foo  # test$foo
NEW_KEY3=test$KEY   # test123

If you want to customize the prefix of env variables, see envPrefix .

Safety Precautions

.env.*.local files should be local and can contain sensitive variables. You should add .local to your .gitignore to avoid them being checked in by git.

Since any variables exposed to the Vite source code will eventually appear in the client package, the VITE_* variables should not contain any sensitive information.

IntelliSense for TypeScript
By default, Vite provides type definitions for import.meta.env in vite/client.d.ts. As you customize more and more environment variables in your .env[mode] files, you may want to get TypeScript intellisense for those user-defined environment variables prefixed with VITE_ in your code.

To do this, you can create an env.d.ts file in the src directory, and then add the ImportMetaEnv definition as follows:

/// <reference types="vite/client" />

interface ImportMetaEnv {
    
    
  readonly VITE_APP_TITLE: string
  // 更多环境变量...
}

interface ImportMeta {
    
    
  readonly env: ImportMetaEnv
}

If your code depends on the type of browser environment, such as DOM and WebWorker, you can modify the lib field in tsconfig.json to get type support.

{
    
    
  "lib": ["WebWorker"]
}

Modes
By default, the development server (dev command) runs in development mode, and the build command runs in production mode.

This means that when vite build is executed, it will automatically load environment variables that may exist in .env.production:

.env.production

VITE_APP_TITLE=My App
In your application, you can use import.meta.env.VITE_APP_TITLE to render the title.

In some cases, if you want to run vite build in a different mode to render different titles, you can override the default mode used by the command by passing the --mode option flag. For example, if you want to build your app in staging (pre-release) mode:

bash
vite build --mode staging
also needs to create a new .env.staging file:

.env.staging

VITE_APP_TITLE=My App (staging)
Since vite build runs production mode builds by default, you can also change it to run development mode builds by using a different mode and corresponding .env file configuration:

.env.testing

NODE_ENV=development

Guess you like

Origin blog.csdn.net/weixin_47287832/article/details/129688327