Search code examples
htmlvitesvelte

controlling css order in vite dev server


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?


Solution

  • 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:

          {
            name: 'move-extension-css-to-end',
            transformIndexHtml(html) {
              return html
                .replace(
                  '    <link rel="stylesheet" href="./extension.css" />\n',
                  ''
                )
                .replace(
                  '  </head>',
                  '    <link rel="stylesheet" href="./extension.css" />\n  </head>'
                );
            },
          },
    

    The first replace removes my style sheet link from where it is placed by Vite. The second replace puts it directly before the 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 the dist folder.