vue项目中修改页面title方法

1,189 阅读1分钟

vue 项目中同时配置 vue.config.js 中的属性修改页面的title

背景:在使用vue搭建项目后,我们经常需要修改项目的title,但是package.json中不能出现中文,所以我们可以在根据不同的情况做配置:

vue-cli

vue.config.js 中做如下的配置:

    module.exports = {
        chainWebpack: (config) => {
            config.plugin('html').tap((args) => {
              args[0].title = `xxxx`
              return args
            })
        }
    }

vite

  1. 首先在项目根目录下创建两个配置文件:

    • .env.development
        # .env.development
        VITE_APP_TITLE = 系统名称
    
    • .env.production
        # .env.production
        VITE_APP_TITLE = 系统名称
    
  2. 安装插件: npm install vite-plugin-html -D

  3. vite.config.js 中做如下配置:

    import { fileURLToPath, URL } from 'node:url'

    import { defineConfig, loadEnv } from 'vite'
    import vue from '@vitejs/plugin-vue'
    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(),
        createHtmlPlugin({
          inject: {
            data: {
              // 将环境变量 VITE_APP_TITLE 赋值给 title 方便 html 页面中使用 title 获取系统标题
              title: getViteEnv(mode, "VITE_APP_TITLE")
            }
          }
        })
      ],
      resolve: {
        alias: {
          '@': fileURLToPath(new URL('./src', import.meta.url))
        }
      },
    })

  1. 在 index.html 中使用环境变量:
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <link rel="icon" href="/favicon.ico" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
         <!-- 修改title -->
        <title><&- title %></title>
      </head>
      <body>
        <div id="app"></div>
        <script type="module" src="/src/main.js"></script>
      </body>
    </html>