Configure Vite’s environment variables and mode (.env mode)

Picture(2).png

Create project

npm create vite@latest

or

yarn create vite

or

pnpm create vite

image.png

environment variables

import.meta.envVite exposes environment variables on a special object.

console.log(import.meta.env)

image.png

built-in variables

  • import.meta.env.MODE: {string} The mode in which the application runs .
  • import.meta.env.BASE_URL: {string} The base URL when deploying the application. It is determined by baseconfiguration items .
  • import.meta.env.PROD: {boolean} Whether the application is running in a production environment.
  • import.meta.env.DEV: {boolean} Whether the application is running in a development environment (always the import.meta.env.PRODopposite).
  • import.meta.env.SSR: {boolean} Whether the application is running on the server .

Create .env file to define variables

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 忽略

创建.env文件

#.env
BASE_HREF="xxx"
VITE_BASE_HREF="yyy"

image.png

To prevent accidentally leaking some environment variables to the client, only variables prefixed VITE_with will be exposed to vite-processed code.

BASE_HREF 没有打印出来,VITE_BASE_HREF 打印出来了

再创建一个.env.development文件

#.env.development
BASE_HREF="mmm"
VITE_BASE_HREF="nnn"

image.png

VITE_BASE_HREF 被覆盖成nnn了

HTML environment variable substitution

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

<title>Vite + Vue + TS %VITE_BASE_HREF%</title>
html js
if the variable does not exist variable name undefined

image.png

model

By default, the development server ( devcommand) runs in development(development) mode and buildthe command runs in production(production) mode.

1、创建.env.test

# .env
BASE_HREF="xxx"
VITE_BASE_HREF="yyy"
VITE_APP_TEST="aaa"
# .env.test
VITE_APP_TEST="test"

2、配置package.json

//package.json

"scripts": {
    
    
    "dev": "vite",
    "test": "vite --mode test",
    "build": "vue-tsc && vite build",
    "build:test": "vue-tsc && vite build --mode test",
    "preview": "vite preview"
  },

3、执行 npm run test

image.png

.envThe contents of both .env.testfiles will be loaded, but .env.testthe .envpriority .envof VITE_APP_TEST is higher, so VITE_APP_TEST is overwritten.

Guess you like

Origin blog.csdn.net/weixin_46318413/article/details/131746127