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

Vite构建时如何排除HTML指定代码片段?插件尝试未生效

在Vite构建中移除HTML指定片段的解决方案

你之前用rollup-plugin-re没效果的核心原因是:Rollup插件默认只处理JS/TS等模块文件,Vite对HTML文件的处理是独立流程,不会让普通Rollup插件介入HTML内容的修改。下面给你两种可行的解决办法:

方法一:自定义简易Vite插件(无额外依赖)

直接在vite.config.ts中添加一个自定义插件,利用Vite的transform钩子处理HTML文件:

import { defineConfig } from "vite";
import { glob } from "glob";

export default defineConfig({
  input: "./index.html",
  plugins: [
    {
      name: "html-exclude-blocks",
      transform(code, id) {
        // 仅对HTML文件执行替换逻辑
        if (id.endsWith(".html")) {
          // 匹配<!-- EXCLUDE_START -->到<!-- EXCLUDE_END -->的所有内容(包含标记本身)
          return code.replace(/<!--\s*EXCLUDE_START\s*-->[\s\S]*?<!--\s*EXCLUDE_END\s*-->/g, "");
        }
        return code;
      },
    },
  ],
  css: {
    preprocessorOptions: {
      scss: {
        api: "modern-compiler",
        loadPaths: glob.sync("./node_modules/{@tras}/*/src/scss"),
      },
    },
  },
  server: {
    proxy: {
      "/wss": {
        target: "",
        changeOrigin: true,
      },
    },
  },
});

原理说明

  • name:插件唯一标识,取一个有意义的名字即可
  • transform:Vite提供的钩子,会在每个文件被编译时触发
  • 正则表达式/<!--\s*EXCLUDE_START\s*-->[\s\S]*?<!--\s*EXCLUDE_END\s*-->/g:非贪婪匹配包含注释标记在内的所有内容,确保只删除指定区块

方法二:使用vite-plugin-html插件(功能更丰富)

如果需要更多HTML处理能力(比如注入变量、压缩代码),可以用专门的HTML插件:

  1. 安装依赖
npm install vite-plugin-html --save-dev
  1. 修改Vite配置
import { defineConfig } from "vite";
import { glob } from "glob";
import { createHtmlPlugin } from "vite-plugin-html";

export default defineConfig({
  input: "./index.html",
  plugins: [
    createHtmlPlugin({
      transform: (code) => {
        // 同样用正则替换指定区块
        return code.replace(/<!--\s*EXCLUDE_START\s*-->[\s\S]*?<!--\s*EXCLUDE_END\s*-->/g, "");
      },
    }),
  ],
  css: {
    preprocessorOptions: {
      scss: {
        api: "modern-compiler",
        loadPaths: glob.sync("./node_modules/{@tras}/*/src/scss"),
      },
    },
  },
  server: {
    proxy: {
      "/wss": {
        target: "",
        changeOrigin: true,
      },
    },
  },
});

验证效果

执行npm run build后,查看dist目录下的index.html,你会发现<!-- EXCLUDE_START -->和<!-- EXCLUDE_END -->之间的内容已经被完全移除。

内容的提问来源于stack exchange,提问作者Aaron Balthaser

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 23:39:58