网站首页 > 知识剖析 正文
在做项目环境变量配置前,可以先到官网回忆一下环境变量的基本使用,https://cn.vitejs.dev/guide/env-and-mode.html
一、环境模式
首先环境变量是可以分模式的,常用模式如下:
.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
更多前端知识,请关注小程序,不定期有惊喜!
猜你喜欢
- 2024-11-24 浏览器跨域问题以及常用解决方案
- 2024-11-24 14个前端小知识,我猜你每天都会遇到
- 2024-11-24 跨域问题的4种解决方案
- 2024-11-24 什么是跨域?跨域解决方法
- 2024-11-24 构建rancher自定义ui的前端镜像
- 2024-11-24 你应该知道的前端小知识,初学者,确定不点进来看看吗?
- 2024-11-24 15个前端小知识
- 2024-11-24 记一场纯JS赛——DiceCTF2021 Web题解
- 2024-11-24 如何基于 Elasticsearch 实现排序沉底或前置
- 2024-11-24 如何查找网站源IP地址
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)