◆
Vite 插件 transformIndexHtml 钩子用法详解
transformIndexHtml
类型:IndexHtmlTransformHook | { enforce?: 'pre' | 'post', transform: IndexHtmlTransformHook }
作用:转换 index.html 的专用钩子。钩子接收当前的 HTML 字符串和转换上下文。上下文在开发期间暴露 ViteDevServer 实例,在构建期间暴露 Rollup 输出的包。
这个钩子可以是异步的,并且可以返回以下其中之一:
- 经过转换的 HTML 字符串
- 注入到现有 HTML 中的标签描述符对象数组(
{ tag, attrs, children })。每个标签也可以指定它应该被注入到哪里(默认是在<head>之前) - 一个包含
{ html, tags }的对象
所以根据官网解释的 api 使用可以用下面两种调用形式
{
// 第一种
transformIndexHtml: {
enforce: ('post', async);
transform(html, ctx);
{
console.log(html, ctx);
}
}
// 第二种
transformIndexHtml(html);
{
console.log(html);
}
}
可以看出来第一种会多一个 enforce 参数,这个是用来控制 transformIndexHtml 执行时顺序的参数

还没有留言,来发表第一条吧~