vite 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} The mode the application runs in .

  • import.meta.env.BASE_URL: {string} The base URL when deploying the application. It is determined by the base configuration item .

  • import.meta.env.PROD: {boolean} Whether the application is running in the production environment.

  • import.meta.env.DEV: {boolean} Whether the application is running in the development environment (always the  import.meta.env.PRODopposite).

  • import.meta.env.SSR: {boolean} Whether the application is running on  the 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, dynamic key values  import.meta.env[key] ​​are 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  etc., for example when  being replaced with  . There are some ways to avoid this problem:Unexpected token"process.env.NODE_ENV"""development": "

  • 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 <wbr> tag , eg: import.meta.<wbr>env.MODE.
     

.env document

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 for specifying patterns (for example  .env.production) will take precedence over generic forms (for example  .env).

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

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

Loaded environment variables are also  import.meta.env exposed to client source code as strings.

To prevent accidentally leaking some environment variables to the client, only variables prefixed VITE_ with will be exposed to vite-processed code. For example, the following environment variables:

VITE_SOME_KEY=123
DB_PASSWORD=foobar

Only  VITE_SOME_KEY it will be exposed as  import.meta.env.VITE_SOME_KEY source code provided to the client, but  DB_PASSWORD not.

console.log(import.meta.env.VITE_SOME_KEY) // 123
console.log(import.meta.env.DB_PASSWORD) // undefined

In addition, Vite uses  dotenv-expand  to expand variables directly. To learn more about the syntax, check out  their documentation .

Note that if you want to use a 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  .local add to yours  .gitignore to avoid them being checked in by git.

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

Intellisense for TypeScript

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

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

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

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

interface ImportMeta {
  readonly env: ImportMetaEnv
}

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

{
  "lib": ["WebWorker"]
}

HTML environment variable substitution

Vite also supports replacing environment variables in HTML files.  Any attribute in can be used in HTML files import.meta.env with a special  syntax:%ENV_NAME%

<h1>Vite is running in %MODE%</h1>
<p>Using data from %VITE_API_URL%</p>

If the environment variable  import.meta.env does not exist in, for example, does not exist  %NON_EXISTENT%, it will be ignored and not replaced, which is  import.meta.env.NON_EXISTENT different from JS, which will be replaced with  undefined.

model

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

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

# .env.production
VITE_APP_TITLE=My App

In your application, you can use  import.meta.env.VITE_APP_TITLE render headers.

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

vite build --mode staging

You also need to create a new  .env.staging file:

# .env.staging
VITE_APP_TITLE=My App (staging)

Since  the default runs production mode builds, you can also  change this to run development mode builds vite build by using a different mode and corresponding  file configuration:.env

# .env.testing
NODE_ENV=development

Guess you like

Origin blog.csdn.net/qq_44848480/article/details/131309616