vitepress
vitepress copied to clipboard
Vite's "transformIndexHtml" hook is not invoked on build
Describe the bug
When building the docs, transformIndexHtml hook is not invoked.
The hook is invoked is dev mode, though.
Reproduction
- Open https://stackblitz.com/edit/vite-sqmglm?file=docs%2F.vitepress%2Fconfig.ts
- Notice
transformIndexHtmlhook which logs "HELLO" when invoked - Run
npm run docs:build - Notice "HELLO" is not printed in the console
- Run
npm run docs:dev - Notice "HELLO" is printed in the console
Expected behavior
transformIndexHtml is invoked when building.
System Info
System:
OS: Windows 10 10.0.19045
CPU: (16) x64 Intel(R) Core(TM) i7-6900K CPU @ 3.20GHz
Memory: 44.41 GB / 63.92 GB
Binaries:
Node: 20.5.1 - C:\Program Files\nodejs\node.EXE
Yarn: 1.22.19 - ~\AppData\Roaming\npm\yarn.CMD
npm: 9.6.6 - C:\Program Files\nodejs\npm.CMD
pnpm: 7.29.3 - C:\ProgramData\chocolatey\bin\pnpm.EXE
Browsers:
Chrome: 119.0.6045.200
Edge: Spartan (44.19041.3636.0), Chromium (120.0.2210.61)
Additional context
Maybe related: https://github.com/vuejs/vitepress/pull/1380
Validations
- [X] Check if you're on the latest VitePress version.
- [X] Follow our Code of Conduct
- [X] Read the docs.
- [X] Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
Just to make sure it's a vitepress bug, here's similar repro with pure vite where it's working fine ("HELLO" is printed in both dev and build): https://stackblitz.com/edit/vitejs-vite-siefzd?file=vite.config.js
The issue is, unlike vite, we don't have an index.html in build 😅 We do have a html kind of template (that we pass to transformHtml hook), it can be passed to transformIndexHtml too maybe.
Anything we can inject script, styles, etc into would do.
Bump (not stale).
+1. I have to do this to make sure local dev build and production build have the same:
In vite.config.js, for dev build:
import { defineConfig } from "vite"
export default defineConfig({
plugins: [
{
transformIndexHtml: { // effective for development build. See also config.js
enforce: 'pre',
transform (html) {
+ return html.replace(
+ /<body>/,
+ `<body class='my-class'>`
)
}
}
}
],
})
In .vitepress/config.js:
export default {
transformHtml (html) { // effective for production build. See also vite.config.js
+ return html.replace(
+ /<body>/,
+ `<body class='my-class'>`
)
},
}