vite-plugin-svelte
vite-plugin-svelte copied to clipboard
Support the `direct` query param
Describe the problem
In Astro we prefer to add <link> tags per component for styles in development mode. This works because Vite will detect a request that has been added via link tag through the Accept header and then injects the direct query param.
For Astro and Vue styles this works because those Vite plugins do not modify the id. Since Svelte creates an id the direct param gets lost.
This means that we cannot use <link> in dev for Svelte, but rather must use a module script which results in a FOUC (flash of unstyled content).
Describe the proposed solution
When generating the cssId, preserve direct query param, if it's included in the importee. https://github.com/sveltejs/vite-plugin-svelte/blob/a6a8e00dcd2fa05f01e7037a8062ad3afe1f7615/packages/vite-plugin-svelte/src/utils/id.ts#L52
Alternatives considered
No alternatives that I am aware of, other than Astro continuing to use <script> and live with the FOUC.
Note that I am willing to submit a PR for this.
Importance
would make my life easier
:+1:
It gets a bit more complicated than just preserving the direct param. Right now vite-plugin-svelte compiles the .svelte files and stores the css in a cache + returns a js module that contains an import to the css id.
The cached css is then returned by the subsequent request to that module.
So requesting the css via direct link before the .svelte file was imported won't work right now. 3 possible solutions to that
- if the cache is empty, compile in load, only take the css output do not cache anything, the import of .svelte will populate the cache afterwards
- refactor the compile+cache logic so that the first request primes the cache, regardless of js or css imported first
- a long term plan is to reorganize how these sub modules are connected https://github.com/sveltejs/vite-plugin-svelte/issues/136 so if we add the css module there to that could also work
Right now i prefer solution 1) as it is the least amount of work.
Thanks, I think this makes sense to me. For what it's worth, Astro does not add <link> before the Svelte module has already been loaded, so I don't think we'd run into the scenario you are describing, if I'm understanding it correctly.
If you always import Foo.svelte first before the browser sends a request to Foo.svelte?svelte&type=style&lang.css it'll work without additional compiling. Others may not be so cautious so it would still make sense to support it.
Can be done in separate PRs to keep the diffs small.
@matthewp is this still something you need/miss?