vue3 vite 环境变量

  • 想要统一配置系统名称 或者其他的,需要在vue3中使用 vite 的环境变量

  • vite 的环境变量 需要创建两个文件(和 vite.config.js 文件同一目录)
    .env.development 这个文件在开发模式中使用
    .env.production 这个文件在生产模式中使用

  • 在 .env.development 文件中 添加系统标题 (以开发模式为例)

#.env.development
VITE_APP_TITLE=系统名称
  • 在 vue 文件中调用
#login.vue
<template>
<span style="font-size: 20px; font-weight: 600">{{ title }}</span>
</template>
<script setup>
//调用环境变量 在 template 中使用 title
const title = import.meta.env.VITE_APP_TITLE;
...

这样就完成了。

  • 如果想要在index.html中使用 环境变量 需要按照以下方式配置
  1. 安装插件:vite-plugin-html
npm install vite-plugin-html -D

说明:-D 表示安装完成后 将插件配置到 package.json 的 devDependencies 中

  1. 在 vite.config.js 中 增加配置
import { defineConfig, loadEnv } from "vite";
import { createHtmlPlugin } from "vite-plugin-html";
//这个配置 为了在html中使用 环境变量
const getViteEnv = (mode, target) => {
return loadEnv(mode, process.cwd())[target];
};
// https://vitejs.dev/config/
export default ({ mode }) =>
defineConfig({
plugins: [
vue(),
HtmlPlugin({
inject: {
data: {
//将环境变量 VITE_APP_TITLE 赋值给 title 方便 html页面使用 title 获取系统标题
title: getViteEnv(mode, "VITE_APP_TITLE"),
},
},
}),
],
server: {
},
});
  1. 在 index.html 中使用 环境变量
<title><%- title %></title>

完成

posted @   代码召唤师  阅读(1322)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· 因为Apifox不支持离线,我果断选择了Apipost!
点击右上角即可分享
微信分享提示