You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vite Vue3模板项目中index.html字符串注入实现方案咨询

Vite中index.html内容注入的两种无额外依赖方案

好问题!在Vite里实现index.html的内容注入,完全不需要额外安装npm包,刚好对应你提到的两种场景:

一、基础环境变量注入(对应vue-cli的<%= BASE_URL %>场景)

Vite内置支持在index.html中直接使用环境变量,语法是用%变量名%包裹:

  • 对于内置的BASE_URL,直接写%BASE_URL%即可,比如:
    <link rel="icon" href="%BASE_URL%favicon.ico">
    
  • 自定义环境变量需要以VITE_开头(比如VITE_APP_TITLE),在.env文件中定义后,直接在index.html中引用:
    <title>%VITE_APP_TITLE%</title>
    
    对应的.env内容:
    VITE_APP_TITLE=我的Vite项目
    

二、通用JS代码/自定义选项注入(对应htmlWebpackPlugin.options.title场景)

如果需要更灵活的逻辑(比如执行JS代码、传递自定义配置),可以利用Vite的transformIndexHtml钩子编写一个极简的自定义插件,完全不需要额外依赖:

步骤1:在vite.config.js中添加自定义插件

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import fs from 'fs'
import path from 'path'

export default defineConfig({
  plugins: [
    vue(),
    {
      name: 'custom-html-transform', // 插件名称,自定义即可
      transformIndexHtml(html, context) {
        // 这里可以写任意JS逻辑,比如读取package.json、判断环境、生成动态内容
        const pkg = JSON.parse(fs.readFileSync(path.resolve(__dirname, 'package.json'), 'utf-8'))
        const customOptions = {
          title: pkg.name || '默认标题',
          isDev: !!context.server, // 判断是否是开发环境
          buildTime: new Date().toLocaleString()
        }

        // 替换index.html中的自定义标记,这里用{{ 变量名 }}作为示例,你可以改成自己习惯的格式
        return html
          .replace(/{{\s*htmlOptions.title\s*}}/, customOptions.title)
          .replace(/{{\s*isDev\s*}}/, customOptions.isDev ? '开发环境' : '生产环境')
          .replace(/{{\s*buildTime\s*}}/, customOptions.buildTime)
      }
    }
  ]
})

步骤2:在index.html中使用自定义标记

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>{{ htmlOptions.title }}</title>
</head>
<body>
  <div id="app"></div>
  <p>当前环境:{{ isDev }}</p>
  <p>构建时间:{{ buildTime }}</p>
  <script type="module" src="/src/main.js"></script>
</body>
</html>

这种方式的灵活性极高,你可以在transformIndexHtml里实现任何你需要的JS逻辑,比如根据不同环境注入不同的脚本、读取外部配置文件等,完全替代webpack中html-webpack-plugin的自定义模板功能。

内容的提问来源于stack exchange,提问作者v-moe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 20:32:48