Table of contents
Create project
npm create vite@latest
or
yarn create vite
or
pnpm create vite
environment variables
import.meta.env
Vite exposes environment variables on a special object.
console.log(import.meta.env)
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 bybase
configuration 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 theimport.meta.env.PROD
opposite).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"
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"
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.env
using special syntax.%ENV_NAME%
<title>Vite + Vue + TS %VITE_BASE_HREF%</title>
html | js | |
---|---|---|
if the variable does not exist | variable name | undefined |
model
By default, the development server ( dev
command) runs in development
(development) mode and build
the 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
.env
The contents of both.env.test
files will be loaded, but.env.test
the.env
priority.env
of VITE_APP_TEST is higher, so VITE_APP_TEST is overwritten.