|
| 1 | +import type { ViteUserConfig } from 'astro'; |
| 2 | +import MagicString from 'magic-string'; |
| 3 | + |
| 4 | +const starlightPageImportSource = '@astrojs/starlight/components/StarlightPage.astro'; |
| 5 | + |
| 6 | +/** |
| 7 | + * Vite plugin that ensures the StarlightPage component is always imported first when imported in |
| 8 | + * an Astro file. |
| 9 | + * |
| 10 | + * This is necessary to ensure a predictable CSS layer order which is defined by the `<Page />` |
| 11 | + * imported by the `<StarlightPage />` component. If a user imports any other component using |
| 12 | + * cascade layers before the `<StarlightPage />` component, it will result in undesired layers |
| 13 | + * being created before we explicitly set the expected layer order. |
| 14 | + */ |
| 15 | +export function vitePluginStarlightCssLayerOrder(): VitePlugin { |
| 16 | + return { |
| 17 | + name: 'vite-plugin-starlight-css-layer-order', |
| 18 | + enforce: 'pre', |
| 19 | + transform(code, id) { |
| 20 | + if ( |
| 21 | + !id.endsWith('.astro') || |
| 22 | + id.endsWith(starlightPageImportSource) || |
| 23 | + code.indexOf('StarlightPage.astro') === -1 |
| 24 | + ) { |
| 25 | + return; |
| 26 | + } |
| 27 | + |
| 28 | + let ast: ReturnType<typeof this.parse>; |
| 29 | + |
| 30 | + try { |
| 31 | + ast = this.parse(code); |
| 32 | + } catch { |
| 33 | + return; |
| 34 | + } |
| 35 | + |
| 36 | + let hasStarlightPageImport = false; |
| 37 | + |
| 38 | + for (const node of ast.body) { |
| 39 | + if (node.type !== 'ImportDeclaration') continue; |
| 40 | + if (node.source.value !== starlightPageImportSource) continue; |
| 41 | + |
| 42 | + const importDefaultSpecifier = node.specifiers.find( |
| 43 | + (specifier) => specifier.type === 'ImportDefaultSpecifier' |
| 44 | + ); |
| 45 | + if (!importDefaultSpecifier) continue; |
| 46 | + |
| 47 | + hasStarlightPageImport = true; |
| 48 | + break; |
| 49 | + } |
| 50 | + |
| 51 | + if (!hasStarlightPageImport) return; |
| 52 | + |
| 53 | + // Format path to unix style path. |
| 54 | + const filename = id.replace(/\\/g, '/'); |
| 55 | + const ms = new MagicString(code, { filename }); |
| 56 | + ms.prepend(`import "${starlightPageImportSource}";\n`); |
| 57 | + |
| 58 | + return { |
| 59 | + code: ms.toString(), |
| 60 | + map: ms.generateMap({ hires: 'boundary' }), |
| 61 | + }; |
| 62 | + }, |
| 63 | + }; |
| 64 | +} |
| 65 | + |
| 66 | +type VitePlugin = NonNullable<ViteUserConfig['plugins']>[number]; |
0 commit comments