在做我的项目环境变量配置前,能够先到官网回顾一下环境变量的根本应用,https://cn.vitejs.dev/guide/e...
一、环境模式
首先环境变量是能够分模式的,罕用模式如下:
.env # 所有状况下都会加载.env.local # 所有状况下都会加载,但会被 git 疏忽.env.[mode] # 只在指定模式下加载.env.[mode].local # 只在指定模式下加载,但会被 git 疏忽
默认 dev
环境下应用 .env.development
环境变量配置,build
环境下应用 .env.production
,所以不须要在 package.json
中再指定模式了
"scripts": { "dev": "vite --mode development", // --mode development能够省略,运行 npm run dev 主动指定 "build": "vue-tsc --noEmit && vite build --mode production", // --mode production能够省略,运行 npm run build 主动指定 "preview": "vite preview"},
--mode
个别在其余非凡自定义下指定应用。
二、环境变量分类
2.1 默认环境变量
- import.meta.env.MODE: {string} 利用运行的模式
- import.meta.env.BASE_URL: {string} 部署利用时的根本 URL
- import.meta.env.PROD: {boolean} 利用是否运行在生产环境
- import.meta.env.DEV: {boolean} 利用是否运行在开发环境 (永远与 import.meta.env.PROD相同)
2.2 利用级环境变量
以 VITE_
结尾,这样会被vite解决,如下:
.env.developlent
VITE_API_URL=/api/VITE_LOCATION_ORIGIN=http://localhost:3000/
另外自定义的环境变量,还须要在 env.d.ts
中申明变量类型
/// <reference types="vite/client" />interface ImportMetaEnv { readonly VITE_TITLE: string readonly VITE_API_URL: string}interface ImportMeta { readonly env: ImportMetaEnv}declare module '*.vue' { import type { DefineComponent } from 'vue' // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types const component: DefineComponent<{}, {}, any> export default component}
三、加载优先级
模式笼罩通用,如:在生产环境下,.env.production
中的同名环境变量会笼罩 .env
中同名配置,其余同理
四、环境变量应用
Vite把环境变量通过 import.meta.env
裸露进去,在 .vue
中应用形式如下:
<script setup lang="ts"> console.log(import.meta.env)</script>
但如果要在 axios 中应用就须要特地配置了,须要在 vite.config.js
中加载环境变量,咱们能够像以下这种形式解决:
import { defineConfig, loadEnv } from 'vite'// https://vitejs.dev/config/export default ({ mode }) => defineConfig({ define: { 'process.env': loadEnv(mode, process.cwd()) },}
这样配置实现后就能够在 plugins 下 axios.ts 中应用了
const { VITE_API_URL} = process.envconst instance = axios.create({ baseURL: VITE_API_URL});export default instance
更多前端常识,请关注小程序,不定期有惊喜!