I have a webpage, that loads a script from a vite dev server.
so at the end of body
I have this tag
<script type="module" src="https://localhost:5173/index.ts"></script>
In general this works fine, and when I build and bundle everything it works perfectly.
However when running it as a dev server, vite throws all css tags into head
.
And it adds a lot of them (one per import I guess).
of course it should add it to head, but my head (before vite has loaded) looks like this
<head>
...
<title>...</title>
<link rel="stylesheet" href="/static/supplier.css">
</head>
and vite adds its’ style after it, which is an issue, since I want the supplier.css
to have priority.
so is there any way to configure vite to add its’ style tags at the beginning of the head tag, or at some other convenient place?
2
Answers
Vite doesn’t natively provide a configuration to control where style tags are inserted into the
<head>
during development. However, you can solve this issue by manually moving the Vite-injected<style>
tags to the beginning of the<head>
using a small script given below:I faced the same issue. My CSS file is named
extension.css
and I have it in public folder, so Vite moves it to root folder. And I want it last in the generated HTML, to give it priority.The plugin turned out to be quite simple to implement:
First replace removes my stylesheet link it from where it is placed by Vite. The second puts it directly before body.
You can make it fancier / more flexible with regex, etc. For me string replacement works just fine. You can find what to replace in the generated HTML file in
dist
folder.