Vite插件中transformIndexHtml钩子为啥不生效?

令狐春依 阅读 3

我在写一个Vite插件,想用transformIndexHtml修改index.html里的内容,但加了console.log都没输出,钩子好像根本没执行。

我的插件代码是这样注册的:

export default function myPlugin() {
  return {
    name: 'my-plugin',
    transformIndexHtml(html) {
      console.log('hook triggered');
      return html.replace('<title>Vite App</title>', '<title>My App</title>');
    }
  };
}

然后在vite.config.js里也正确引入了。奇怪的是build的时候也不报错,就是没效果。是我用错钩子了吗?还是这个钩子只在特定模式下才触发?

我来解答 赞 3 收藏
二维码
手机扫码查看
1 条解答
爱学习的梓希
你的问题很可能是 Vite 版本导致的。

如果你是 Vite 3.x 或 4.x,transformIndexHtml 这个钩子已经被移除了,不再生效。Vite 2.x 才用这个钩子。

改成这样:

export default function myPlugin() {
return {
name: 'my-plugin',
transform(code, id) {
if (id.endsWith('index.html')) {
console.log('hook triggered');
return code.replace('<title>Vite App</title>', '<title>My App</title>');
}
}
};
}


或者用 enforce: 'pre' 确保在其他插件之前执行:

export default function myPlugin() {
return {
name: 'my-plugin',
transform(code, id) {
if (!id.includes('index.html')) return;

return code.replace('<title>Vite App</title>', '<title>My App</title>');
},
enforce: 'pre'
};
}


还有一点:这个钩子只在 dev 服务器启动时生效,build 构建时不会触发。如果你想在构建时也修改 HTML,得用 generateBundle 钩子:

generateBundle(options, bundle) {
const html = bundle['index.html'];
if (html && html.source) {
html.source = html.source.toString().replace(
'<title>Vite App</title>',
'<title>My App</title>'
);
}
}


你现在用的是哪个版本的 Vite?确认一下版本,很多人不生效就是因为版本升级后 API 变了。
点赞
2026-03-18 09:02