UNPKG

@unocss/astro

Version:

UnoCSS integration for Astro

66 lines (65 loc) 2.62 kB
import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import VitePlugin from "@unocss/vite"; import { normalizePath } from "vite"; //#region src/index.ts const UNO_INJECT_ID = "uno-astro"; const WIND3_RESET_CSS = "@unocss/reset/tailwind.css"; /** * When presetWind4 is detected in the resolved config, remove the Wind 3 reset * injection (`@unocss/reset/tailwind.css`) from the injects array, since Wind 4 * handles its own reset via the preflight system. */ async function reconcileResetInjects(ctx, injects) { if ((await ctx.getConfig()).presets?.some((p) => p.name === "@unocss/preset-wind4")) { const resetIndex = injects.findIndex((s) => s.includes(WIND3_RESET_CSS)); if (resetIndex !== -1) injects.splice(resetIndex, 1); } } function AstroVitePlugin(options) { const { injects } = options; let root; let ctx; return { name: "unocss:astro", enforce: "pre", async configResolved(config) { root = config.root; const api = config.plugins.find((i) => i.name === "unocss:api")?.api; if (!api) throw new Error("[@unocss/astro] Unable to find UnoCSS Vite plugin API."); ctx = api.getContext(); await reconcileResetInjects(ctx, injects); }, async resolveId(id, importer) { const { RESOLVED_ID_RE } = await ctx.getVMPRegexes(); if (RESOLVED_ID_RE.test(id)) return this.resolve(normalizePath(join(root, id)), importer, { skipSelf: true }); if (id === UNO_INJECT_ID) return id; }, load(id) { if (id.endsWith(UNO_INJECT_ID)) return injects.join("\n"); } }; } function UnoCSSAstroIntegration(options = {}, defaults) { const { injectEntry = true, injectReset = false, injectExtra = [] } = options; return { name: "unocss", hooks: { "astro:config:setup": async ({ config, updateConfig, injectScript }) => { const source = resolve(fileURLToPath(config.srcDir), "components/**/*").replace(/\\/g, "/"); options.content ||= {}; options.content.filesystem ||= []; options.content.filesystem.push(source); const injects = []; if (injectReset) { const resetPath = typeof injectReset === "string" ? injectReset : WIND3_RESET_CSS; injects.push(`import ${JSON.stringify(resetPath)}`); } if (injectEntry) injects.push(typeof injectEntry === "string" ? injectEntry : "import \"uno.css\""); if (injectExtra.length > 0) injects.push(...injectExtra); updateConfig({ vite: { plugins: [AstroVitePlugin({ injects }), ...VitePlugin(options, defaults)] } }); if (injects?.length) injectScript("page-ssr", `import ${JSON.stringify(UNO_INJECT_ID)}`); } } }; } //#endregion export { UnoCSSAstroIntegration as default };