@@ -96,7 +96,66 @@ function generateTags (assets) {
9696 return { cssTags, jsTags }
9797}
9898
99+ /**
100+ * Generate a script tag to fix CSS ordering issues in development mode
101+ * @param {Array<string> } selectors - CSS selectors for elements that should come after Vite's CSS
102+ * @param {string } nonce - CSP nonce to allow script execution
103+ * @returns {string } - Script tag for reordering CSS
104+ */
105+ function generateCssOrderFixer ( selectors , nonce = '' ) {
106+ if ( process . env . NODE_ENV === 'production' ) {
107+ return '' // No need for this in production
108+ }
109+
110+ const selectorsJson = JSON . stringify ( selectors )
111+ const nonceAttr = nonce ? ` nonce="${ nonce } "` : ''
112+
113+ return `<script${ nonceAttr } >
114+ // Function to run the fix
115+ function attemptFixCssOrder() {
116+ const head = document.head;
117+ const cssSelectors = ${ selectorsJson } ;
118+
119+ // Find all target elements
120+ const targetElements = cssSelectors
121+ .map(selector => head.querySelector(selector))
122+ .filter(el => el !== null);
123+
124+ if (targetElements.length) {
125+ // Find all vite-injected styles
126+ const viteStyles = Array.from(head.querySelectorAll('style'))
127+ .filter(style => style.dataset.viteDevId);
128+
129+ // Find the first target element to place vite styles before
130+ const firstTarget = targetElements[0];
131+
132+ // Move all vite styles before the first target element
133+ if (viteStyles.length > 0) {
134+ viteStyles.forEach(style => {
135+ head.insertBefore(style, firstTarget);
136+ });
137+ }
138+ }
139+ }
140+
141+ // Run immediately when DOM content is loaded
142+ document.addEventListener("DOMContentLoaded", attemptFixCssOrder);
143+
144+ // Also run after a delay to catch any styles injected after DOMContentLoaded
145+ setTimeout(attemptFixCssOrder, 500);
146+
147+ // Run again after 2 seconds to catch any delayed style injections
148+ setTimeout(attemptFixCssOrder, 2000);
149+
150+ // Monitor for Vite HMR updates and reapply when they happen
151+ window.addEventListener('vite:beforeUpdate', () => {
152+ setTimeout(attemptFixCssOrder, 100);
153+ });
154+ </script>`
155+ }
156+
99157module . exports = {
100158 getViteAssets,
101- generateTags
159+ generateTags,
160+ generateCssOrderFixer
102161}
0 commit comments