在做項目環境變量配置前,可以先到官網回憶一下環境變量的基本使用, 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.env const instance = axios.create({ baseURL: VITE_API_URL }); export default instance
以上就是本次分享的所有內容,想要了解更多歡迎前往公衆號:web前端開發社區,每日干貨分享