当前位置: 首页 > Web前端 > vue.js

vue3+ts+vite2环境变量应该这样使用

时间:2023-03-31 23:50:43 vue.js

在配置项目环境变量之前,可以先去官网回顾一下环境变量的基本使用,https://cn.vitejs.dev/guide/e...1.环境模式首先,环境变量可以分为modes,常用的模式如下:.env#在所有情况下都会加载env.local#在所有情况下都会加载,但是会被git.env忽略。[mode]#只在指定模式下加载.env.[mode].local#只在指定模式下加载,但会被git忽略。默认dev环境使用.env.development环境变量配置,build环境使用.env.production,所以不需要在package.json中指定mode"scripts":{"dev":"vite--modedevelopment",//--modedevelopment可以省略,运行npmrundev自动指定"build":"vue-tsc--noEmit&&vitebuild--modeproduction",//--modeproduction可以省略,运行npmrunbuild自动指定"preview":"vitepreview"},--mode一般为其他特殊定制指定。2.环境变量分类2.1默认环境变量import.meta.env.MODE:{string}应用运行模式import.meta.env.BASE_URL:{string}部署应用时的基本URLimport.meta.env.PROD:{boolean}应用是否运行在生产环境import.meta.env.DEV:{boolean}应用是否运行在开发环境(始终与import.meta.env.PROD相反)2.2应用级环境变量以VITE_,会被vite处理,如下:.env.developpletVITE_API_URL=/api/VITE_LOCATION_ORIGIN=http://localhost:3000/除了自定义环境变量外,还需要在env.d.ts中声明变量类型///interfaceImportMetaEnv{readonlyVITE_TITLE:stringreadonlyVITE_API_URL:string}interfaceImportMeta{readonlyenv:ImportMetaEnv}declaremodule'*.vue'{importtype{DefineComponent}from'vue'//eslint-disable-next-line@typescript-eslint/no-explicit-any,@typescript-eslint/ban-typesconstcomponent:DefineComponent<{},{},any>exportdefaultcomponent}3.加载优先模式覆盖common,如:在生产环境中,环境变量同.env.production中的name会覆盖.env中同名的配置,其余相同。4、环境变量使用Vite通过import.meta.env暴露环境变量,在.vue中使用如下:但是如果要在axios中使用,需要特殊配置,需要在vite.config.js中加载环境变量,我们可以这样处理:import{defineConfig,loadEnv}from'vite'//https://vitejs.dev/config/exportdefault({mode})=>defineConfig({define:{'process.env':loadEnv(mode,process.cwd())},}配置完成后可以在插件下的axios.ts中const{VITE_API_URL}=process.envconstinstance=axios.create({baseURL:VITE_API_URL});导出默认实例https://fenxianglu.cn/