skip to Main Content

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


  1. 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:

    <script>
      document.addEventListener("DOMContentLoaded", () => {
        const head = document.head;
        const supplierStyles = head.querySelector('link[href="/static/supplier.css"]');
        if (supplierStyles) {
          const viteStyles = Array.from(head.querySelectorAll('style'))
            .filter(style => style.dataset.viteDev); // Vite-injected styles have this attribute
          viteStyles.forEach(style => {
            head.insertBefore(style, supplierStyles); // Move Vite styles before supplier.css
          });
        }
      });
    </script>
    
    Login or Signup to reply.
  2. 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>'
                );
            },
          },
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search