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中使用 环境变量 需要按照以下方式配置
安装插件:vite-plugin-html
npm install vite-plugin-html -D说明:-D 表示安装完成后 将插件配置到 package.json 的 devDependencies 中
在 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: {
},
});在 index.html 中使用 环境变量
<title><%- title %></title>完成
本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!