sveltejs / kit

web development, streamlined
https://kit.svelte.dev
MIT License
18.39k stars 1.88k forks source link

Vite's transformIndexHtml hook does not work in SvelteKit. #8619

Closed jacob-8 closed 1 year ago

jacob-8 commented 1 year ago

Describe the bug

Vite's transformIndexHtml hook does not work in SvelteKit. It does in Vite + Svelte, but not in SvelteKit. This hook should be able to update SvelteKit's app.html file.

Reproduction

https://stackblitz.com/edit/sveltejs-kit-template-default-5swnv5?file=vite.config.js&terminal=dev

Logs

No response

System Info

System:
    OS: Linux 5.0 undefined
    CPU: (8) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 0 Bytes / 0 Bytes
    Shell: 1.0 - /bin/jsh
  Binaries:
    Node: 16.14.2 - /usr/local/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 7.17.0 - /usr/local/bin/npm
  npmPackages:
    @sveltejs/adapter-auto: ^1.0.0 => 1.0.0 
    @sveltejs/kit: ^1.0.0 => 1.0.11 
    svelte: ^3.54.0 => 3.55.1 
    vite: ^4.0.0 => 4.0.4

Severity

serious, but I can work around it

Additional Information

This core Vite feature is critical to a plugin I'm building which needs to place styles into the head tag before styles added by SvelteKit (%sveltekit.head%) for CSS specificity control. My workaround is to write using the filesystem... which is messy and will require all plugin changes to be checked into source control every time a value changes.

Rich-Harris commented 1 year ago

transformIndexHtml is designed to operate on a complete HTML document. It can't be used during SSR because then your production app would depend on Vite (and all your plugins); even if that were possible (which it isn't in serverless environments) it's definitely not something to be desired.

Maybe we could manually run those plugin hooks on app.html, but it feels like scenario-solving. Could you use transformPageChunk in handle instead? https://kit.svelte.dev/docs/hooks#server-hooks-handle

jacob-8 commented 1 year ago

Could you use transformPageChunk in handle instead?

Pardon the extra noise. After posting, I saw dominikg's same comment, and worked out a solution along the lines of your suggestion: https://github.com/unocss/unocss/pull/2061#issuecomment-1397869075

I like the idea of SvelteKit running transformIndexHtml automatically inside it's server hooks handle as that would save users one setup step. Presently, users can just set up the hook themselves but I'd give my +1 to SvelteKit automatically running that Vite hook.

For context, I'm placing some global styles into the head (preflights, forms, typography) that I want to come before global styles added by components so the component styles have greater CSS specificity. Why are my component styles leaking out you ask? For use cases like detecting right-to-left defined in a parent component or passing styles down to a child component.