Vite 构建的 Vue 项目配置系统标题

2024-10-12前端1 分钟177 次阅读
AI 摘要salmon-ai

本文讲解了在 Vite 构建的 Vue 项目中如何让 `index.html

教程

如果想要在 index.html 中使用环境变量,需要按照以下方式配置。

  1. 安装插件:vite-plugin-html
bash 复制代码
npm install vite-plugin-html -D
  1. 在vite.config.js中增加配置
js 复制代码
import {fileURLToPath, URL} from 'node:url'

import {defineConfig} from 'vite'
import legacy from '@vitejs/plugin-legacy'
import vue2 from '@vitejs/plugin-vue2'
import {createHtmlPlugin} from "vite-plugin-html";

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [
        vue2(),
        legacy({
            targets: ['ie >= 11'],
            additionalLegacyPolyfills: ['regenerator-runtime/runtime']
        }),
        createHtmlPlugin({
            inject: {
                data: {
                    //将环境变量 VITE_APP_TITLE 赋值给 title 方便 html页面使用 title 获取系统标题
                    title: "测试标题"
                },
            },
        }),
    ],
    resolve: {
        alias: {
            '@': fileURLToPath(new URL('./src', import.meta.url))
        }
    },
    // 反向代理
    server: {
        port: 3000,
        proxy: {
            '/api': {
                target: 'http://127.0.0.1:9999',	//实际请求地址
                changeOrigin: true,
            },
        }
    }
})
  1. 在index.html中使用环境变量
html 复制代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/tianmao.png" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title><%- title %></title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.js"></script>
  </body>
</html>
  1. 效果
    image.png
觉得有用就点个赞,不用登录也能读

评论

0 条
登录 之后才能评论
—
还没有评论,来说第一句