Support some way of inlining CSS into the HTML
See original GitHub issueClear and concise description of the problem
I would like some way to have a CSS file compiled by Vite end up as an inline <style>
tag in the resulting .html file. But without dumping everything into the html like vite-plugin-singlefile.
I have a lightweight splash/loading screen built into my html so the user doesn’t see a blank white page while JS is loading. This needs a bit of CSS, however if this CSS is located in a separate CSS file there is an undesirable FOUC in between when the HTML for the loading screen’s and when the separate delayed network request for the loading screen’s CSS. So it’s strongly desirable to include the loading screen’s CSS inline with the loading screen HTML.
This however is not possible in Vite. In fact Vite actively does the opposite, any inline <style>
styles in html get extracted out into an external stylesheet.
Suggested solution
We already have ?inline
which has a similar behaviour in JS, i.e. return it raw instead of bundling it into a file. So one idea might be to make ?inline
on an @import
in <style>
inline those styles into the <style>
tag the import is present in.
<style>
@import url('./style.css?inline');
</style>
Alternative
I thought the easiest way to implement this as a plugin and tried implementing it in multiple ways. However this turned out to be absurdly difficult.
- A pre transform plugin doesn’t get CSS compiled by the user’s postcss plugins and have to re-implement all of Vite’s CSS handling.
- A post transform plugin doesn’t get the CSS at all, instead it gets a junk ES module so it can’t extract it.
- Vite has no way to append a postcss plugin without overriding the user’s postcss config, so you can’t add a PostCSS that’ll extract something like
@media inline { ... }
either.
Additional context
No response
Validations
- Follow our Code of Conduct
- Read the Contributing Guidelines.
- Read the docs.
- Check that there isn’t already an issue that request the same feature to avoid creating a duplicate.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:18
- Comments:9 (4 by maintainers)
Top GitHub Comments
I face a similar issue (can it be considered the same?) where I’d like a tag
<style>
to remain in the end bundle, mainly because it’s embed in a SVG spritesheet, but Vite strips it from the build HTML and move it to the bundled CSS file.Sample HTML:
The
<style>
tag is moved and the end of the CSS, and I don’t want that:Maybe a solution could be to have a magic comment and/or a setting to keep inline CSS in the HTML and/or what @dantman is suggesting.
For me, Vite 2.9.7 solves the issue. Many thanks to the contributors. 🙇