vitepress icon indicating copy to clipboard operation
vitepress copied to clipboard

Vite's "transformIndexHtml" hook is not invoked on build

Open elringus opened this issue 1 year ago • 5 comments

Describe the bug

When building the docs, transformIndexHtml hook is not invoked.

The hook is invoked is dev mode, though.

Reproduction

  1. Open https://stackblitz.com/edit/vite-sqmglm?file=docs%2F.vitepress%2Fconfig.ts
  2. Notice transformIndexHtml hook which logs "HELLO" when invoked
  3. Run npm run docs:build
  4. Notice "HELLO" is not printed in the console
  5. Run npm run docs:dev
  6. Notice "HELLO" is printed in the console

74a816b8b310188762685e6ffd91d64a

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

elringus avatar Dec 09 '23 22:12 elringus

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

746ce6921d7c949bfc9670d87a51a7d3

elringus avatar Dec 14 '23 02:12 elringus

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.

brc-dd avatar Dec 31 '23 06:12 brc-dd

Anything we can inject script, styles, etc into would do.

elringus avatar Dec 31 '23 11:12 elringus

Bump (not stale).

elringus avatar Feb 10 '24 11:02 elringus

+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'>`
    )
  },
}

Yc-Chen avatar Feb 14 '24 09:02 Yc-Chen