vue3vite系统标题系统名称统一配置

博客 分享
0 219
优雅殿下
优雅殿下 2022-05-07 11:58:55
悬赏:0 积分 收藏

vue3 vite 系统标题 系统名称统一配置

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

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

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

#.env.developmentVITE_APP_TITLE=系统名称 
  • 在 vue 文件中调用
#login.vue<template>  <span >{{ 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 @ 2022-05-07 11:45 代码召唤师 阅读(0) 评论(0) 编辑 收藏 举报
回帖
    优雅殿下

    优雅殿下 (王者 段位)

    2018 积分 (2)粉丝 (47)源码

    小小码农,大大世界

     

    温馨提示

    亦奇源码

    最新会员