Skip to content

Unable to load UnoCSS style with @apply and --at-apply #16373

Closed

Description

@lanxizhu

Astro Info

Astro                    v6.1.7
Vite                     v7.3.2
Node                     v22.22.0
System                   Linux (x64)
Package Manager          pnpm
Output                   static
Adapter                  none
Integrations             unocss (v66.6.8)

If this issue only occurs in one browser, which browser is a problem?

Chrome

Describe the Bug

I've prepared a minimal reproduction:
https://stackblitz.com/edit/withastro-astro-vfyunask?file=package.json

Steps to reproduce:

  1. Open links in browser window.

  2. Wait for the dev servers to start.

  3. Use UnoCSS Directives transformer.

    // uno.config.js
    import { defineConfig, presetWind4, transformerDirectives } from "unocss";
        
    export default defineConfig({
      presets: [presetWind4()],
          
      transformers: [transformerDirectives()],
    });
  4. The custom compontnt uses @apply and --at-apply.

  5. Click Home or Page.

2026-04-17.11.36.37.mov

What's the expected result?

The UnoCSS styles are loaded as expected.

Link to Minimal Reproducible Example

https://stackblitz.com/edit/withastro-astro-vfyunask?file=package.json

Participation

  • I am willing to submit a pull request for this issue.

Activity

  1. astrobot-houston commented on Apr 17, 2026

    @astrobot-houston
    Contributor

    I was able to reproduce this issue. When using UnoCSS's transformerDirectives (which processes @apply and --at-apply) alongside Astro's View Transitions (ClientRouter), styles break on soft navigations. The root cause is twofold: (1) Astro's dev CSS plugin caches CSS content in its transform hook before integration plugins like UnoCSS have processed directives such as @apply, so the cache stores raw unresolved directives instead of the final utility classes; and (2) during ClientRouter soft navigations, Astro's style persistence logic only preserved Vue-style <style> elements but not Astro component styles, causing processed styles to be replaced with their unprocessed raw versions from the new document.

    I was able to fix this issue. The fix extracts the CSS caching transform into a separate plugin (astro:dev-css-cache) that is registered in the Vite plugin chain after integration plugins, ensuring it caches fully-processed CSS. It also extends the style persistence logic in swap-functions.ts to auto-persist Astro component <style> elements (matching ?astro&type=style&...lang.css) during ClientRouter navigations, preventing them from being replaced by unprocessed versions. View Suggested Fix

    P4: important. This bug affects any user combining UnoCSS directive transforms (@apply/--at-apply) with Astro's View Transitions in dev mode — a common setup for Tailwind-like utility workflows. Styles silently break on every soft navigation, making the dev experience unusable for this combination. It does not affect production builds (which use Rollup and process transforms correctly).

    Full Triage Report

    Reproduction

    The issue occurs in astro dev when using UnoCSS's transformerDirectives with @apply/--at-apply and Astro View Transitions (ClientRouter). On the initial page load, styles render correctly. After a soft navigation (clicking a link), UnoCSS-processed styles disappear.

    Diagnosis

    Root Cause 1 — CSS cache ordering (packages/astro/src/vite-plugin-css/index.ts)

    The astro:dev-css plugin included a transform hook that cached CSS content by module ID. This transform ran as part of Astro's core plugin set, which is registered before integration plugins in the Vite config. UnoCSS's transformerDirectives processes @apply directives during its own transform hook. Because Vite executes plugin transforms in registration order, Astro's cache captured the CSS before UnoCSS had resolved the @apply directives. When the ClientRouter requested CSS for a new route, it served the cached (unprocessed) content containing raw @apply — which browsers cannot interpret.

    Root Cause 2 — Style persistence during navigation (packages/astro/src/transitions/swap-functions.ts)

    During ClientRouter soft navigations, persistedHeadElement auto-persists certain <style> elements to avoid replacing HMR-applied (fully-processed) styles with raw (unprocessed) versions from the server-rendered HTML. This logic only matched Vue dev styles (?vue&type=style&...lang.css) but not Astro component styles (?astro&type=style&...lang.css). Astro component styles processed by UnoCSS were therefore replaced on every navigation.

    Fix

    File: packages/astro/src/vite-plugin-css/index.ts

    • Extracted the CSS caching transform into a new standalone plugin astro:dev-css-cache
    • The new plugin shares the same cssContentCache Map via closure
    • Changed astroDevCssPlugin to return { plugins, cssCachePlugin } instead of a flat plugin array

    File: packages/astro/src/core/create-vite.ts

    • Registers devCss.plugins in the normal plugin position
    • Pushes devCss.cssCachePlugin to the end of the plugin array after integration plugins have been merged, ensuring integration transforms (UnoCSS, etc.) run before caching

    File: packages/astro/src/transitions/swap-functions.ts

    • Extended the style persistence regex to also match Astro component styles: /\?astro&type=style&.*lang\.css$/

    This report was made by an LLM. Mistakes happen, check important info.

  2. added
    - P4: important
    pkg: astro
    and removed
    triage: needs triage
    on Apr 17, 2026
  3. added
    triage: needs triage
    on Apr 18, 2026
  4. martrapp commented on Apr 18, 2026

    @martrapp
    Member

    @astrobot-houston, you ran your triage on an older version of astro. Swap functions have ben changed yesterday. could please re-triage with the current state?

  5. astrobot-houston commented on Apr 18, 2026

    @astrobot-houston
    Contributor
    • Reproduced: Yes — on current main (including swap-functions changes from PR Improves Vue scoped style handling in DEV mode during client router navigation. #16379).
    • Exploration: Yes — View branch
    • Priority: P4: important. This affects any user combining UnoCSS directive transforms (@apply/--at-apply) with Astro's ClientRouter in dev mode — a common Tailwind-like utility workflow. Styles silently break on every soft navigation, making the dev experience unusable for this combination.

    The root cause is twofold: (1) Astro's astro:dev-css plugin caches CSS in its transform hook before integration plugins like UnoCSS have processed directives such as @apply, so the cache stores raw unresolved directives instead of the final utility classes; and (2) during ClientRouter soft navigations, the style persistence logic (updated in PRs #16242 and #16379) only preserves Vue scoped <style> elements but not Astro component styles, so the HMR-processed styles get replaced with unprocessed versions from the server-rendered HTML. Production builds are not affected.

    I found a potential fix for this issue. The fix extracts the CSS caching transform into a separate plugin (astro:dev-css-cache) registered after integration plugins, ensuring the cache stores fully-processed CSS. It also extends the style persistence logic to handle Astro component styles (?astro&type=style) during ClientRouter navigations as defense-in-depth. All existing CSS and view-transition tests pass.

    Full Triage Report

    Reproduction

    The issue occurs in astro dev when using UnoCSS's transformerDirectives with @apply/--at-apply and Astro View Transitions (ClientRouter). On initial page load, styles render correctly. After a soft navigation (clicking a link), UnoCSS-processed styles disappear because the <style> element gets replaced with its raw, unprocessed version containing literal @apply directives.

    Baseline Verification

    • Hard page loads always work correctly (styles are properly resolved)
    • Direct UnoCSS utility classes on elements (e.g., class="bg-red-500 p-10 m-10") work correctly even after soft navigation — the issue is specific to @apply/--at-apply directive-transformed styles within component <style> blocks
    • Production builds (astro build) are not affected

    Root Cause Analysis

    Root Cause 1: CSS Cache Ordering (Primary Issue)

    File: packages/astro/src/vite-plugin-css/index.ts, lines 256-275

    The astro:dev-css plugin's transform hook caches CSS content by module ID. This plugin is registered at create-vite.ts:190 in Astro's core plugin array, before integration plugins (UnoCSS) are merged at create-vite.ts:320 via vite.mergeConfig(). Vite runs transform hooks in plugin registration order, so:

    1. Astro's astro:dev-css transform runs first → cssContentCache.set(id, code) stores raw CSS containing @apply
    2. UnoCSS's transformerDirectives transform runs after → resolves @apply into actual CSS properties
    3. The fully-processed CSS goes to Vite's module graph, but cssContentCache retains the raw version

    When the ClientRouter fetches CSS for a new route via the dev CSS virtual module, it reads from cssContentCache (line 237), which contains the unprocessed version. On initial hard page load, this raw inline <style> gets overridden by Vite's client-side CSS module system, which executes all transforms in the correct order. The problem only manifests during soft navigation.

    Introduced by the Environment API refactor (commit 141c4a26419, PR #14306). No comment or evidence that integration transform ordering was considered.

    Root Cause 2: Style Non-Persistence During Soft Navigation

    File: packages/astro/src/transitions/swap-functions.ts, lines 58-85 and 190-245

    PR #16379 added two mechanisms for Vue scoped styles that do not extend to Astro component styles:

    • persistedHeadElement (lines 221-226): Only matches Vue scoped styles via vueScopedStyleId(). Astro component styles (?astro&type=style&index=0&lang.css) are not matched.
    • knownVueScopedStyles map (lines 11, 66-70, 77-84): Before removing old styles, Vue scoped styles are saved for reuse. Astro component styles are not saved.

    PR #16242 deliberately narrowed persistedHeadElement from matching all data-vite-dev-id styles to only Vue styles because UnoCSS's /__uno.css has the same ID on every page but with different content. This narrowing was correct for /__uno.css but overly broad — it also excluded Astro component styles, which have stable content when the same component appears on multiple pages.

    Fix Details

    Fix 1: CSS Cache Plugin Ordering (Primary)

    packages/astro/src/vite-plugin-css/index.ts: Extracted the CSS caching transform hook into a separate standalone plugin astro:dev-css-cache. The function now returns { plugins, cssCachePlugin } instead of a flat Plugin[] array. The cache plugin shares the same cssContentCache Map via closure.

    packages/astro/src/core/create-vite.ts: Registers devCss.plugins in the normal position. Pushes devCss.cssCachePlugin to the end of the plugin array after integration plugins have been merged, ensuring integration transforms run before caching.

    Fix 2: Astro Component Style Persistence (Complementary)

    packages/astro/src/transitions/swap-functions.ts:

    • Added astroComponentStyleId() function (analogous to vueScopedStyleId()) matching ?astro + type=style in data-vite-dev-id
    • Extended persistedHeadElement() to also persist Astro component styles
    • Added knownAstroComponentStyles map (analogous to knownVueScopedStyles)
    • Updated swapHeadElements() to check both maps when appending new elements

    /__uno.css is NOT affected because it does not match the ?astro&type=style pattern.

    Test Update

    packages/astro/test/0-css.test.js: Updated "resolves CSS from Vue" test assertion to account for Vue scoped styles now including the data-v- scope attribute in cached CSS.

    Verification

    • Inline <style> in server-rendered HTML now contains fully-resolved CSS instead of raw @apply
    • All existing tests pass: 0-css.test.js (38 pass), css-dynamic-import-dev.test.js, view-transitions.test.js, css-order*.test.js, page-level-styles.test.js, postcss.test.js, tailwindcss.test.js, scoped-style-strategy.test.js, units/render/transitions.test.ts (26 pass)

    This report was made by an LLM. The analysis may be wrong, and the potential fix might not work, but is intended as a starting point for exploring the issue.

  6. removed
    triage: needs triage
    on Apr 18, 2026
  7. added
    - P3: minor bug
    and removed
    - P4: important
    on Apr 18, 2026
  8. martrapp commented on Apr 18, 2026

    @martrapp
    Member

    This seems to become a never endig story.

    We already had a version where the client router persisted all styles, including unoCSS. (#16204)
    The consequence was that unoCSS did not work at all, as new styles from the server were not updated.

    The fix (#16242) was to explicitely exclude unoCSS and all non Vue styles from auto-persistence.

    Houstons proposal to cache all astro styles might help for @apply but it will most likely harm unoCSS in general.

    I have no idea what the proposed change to vites pipeline does and I'm pretty sure I will not mess with that ;-) Specialists welcome!

    There is no problem for production, "only" in DEV mode. Page refresh gets the styles right.

    What we see here is that the vite ecosystem does cool things with module scripts and and we hit some technical limitations of what the client router can do. We are not able to reload module scripts during soft navigation in the same way as the browser does on MPA navigation.

    I am open for good ideas on how to solve this! In the meantime, watch out for https://bugzilla.mozilla.org/show_bug.cgi?id=1860854 which will hopefully be closed this year (as part of Interop 2026) and brings browser native cross document view transitions to all major browsers.

  9. added
    triage: needs triage
    on May 15, 2026
  10. matthewp commented on May 15, 2026

    @matthewp
    Contributor

    Astrobot, please rereview this issue and if the fix still works, do a preview release

  11. added
    triage: fix pending
    on May 15, 2026
  12. astrobot-houston commented on May 15, 2026

    @astrobot-houston
    Contributor
    • Reproduced: Yes — on current main (Astro v6.3.3).
    • Exploration: Yes — View branch
    • Unit Test: Yes — test/units/dev/css-cache-plugin-ordering.test.ts
    • Priority: P4: important. This affects any user combining UnoCSS directive transforms (@apply/--at-apply) with Astro's ClientRouter in dev mode — a common Tailwind-like utility workflow. Styles silently break on every soft navigation, making the dev experience unusable for this combination. Production builds and hard page loads are not affected.

    The root cause is in the Vite plugin ordering for CSS caching. Astro's astro:dev-css plugin caches CSS in its transform hook, which runs before integration plugins like UnoCSS in the Vite pipeline. This means the cache stores raw @apply directives instead of the resolved CSS. During ClientRouter soft navigations, the server serves HTML with these unprocessed styles — which browsers cannot interpret. This fix does not touch swap-functions.ts or the style persistence logic, respecting @martrapp's feedback about the risks of persisting non-Vue styles.

    I found a potential fix for this issue. The fix extracts the CSS caching transform into a separate plugin (astro:dev-css-cache) that is registered in the Vite plugin chain after integration plugins are merged, ensuring the cache stores fully-processed CSS. All existing CSS and view-transition tests pass (100+ tests across 10 test suites).

    Try this fix

    You can test this fix right now without waiting for a release:

    npm i https://pkg.pr.new/astro@2dd544c
    

    If this fixes your issue, please leave a comment letting us know (e.g. "confirmed, this fixes it"). We'll then open a pull request to get this merged.

    Full Triage Report

    Reproduction

    The issue occurs in astro dev when using UnoCSS's transformerDirectives with @apply/--at-apply and Astro View Transitions (ClientRouter). On initial page load, styles render correctly. After a soft navigation (clicking a link), UnoCSS-processed styles disappear because the <style> element gets replaced with its raw, unprocessed version containing literal @apply directives.

    Baseline Verification

    • Hard page loads always work correctly (styles are properly resolved)
    • Direct UnoCSS utility classes on elements (e.g., class="bg-red-500 p-10 m-10") work correctly even after soft navigation — the issue is specific to @apply/--at-apply directive-transformed styles within component <style> blocks
    • Production builds (astro build) are not affected

    Root Cause Analysis

    Root Cause: CSS Cache Ordering

    File: packages/astro/src/vite-plugin-css/index.ts, lines 256-272

    The astro:dev-css plugin's transform hook caches CSS content by module ID. This plugin is registered at create-vite.ts:205 in Astro's core plugin array, before integration plugins (UnoCSS) are merged at create-vite.ts:335 via vite.mergeConfig(). Vite runs transform hooks in plugin registration order, so:

    1. Astro's astro:dev-css transform runs first → cssContentCache.set(id, code) stores raw CSS containing @apply
    2. UnoCSS's transformerDirectives transform runs after → resolves @apply into actual CSS properties
    3. The fully-processed CSS goes to Vite's module graph, but cssContentCache retains the raw version

    When the ClientRouter fetches CSS for a new route via the dev CSS virtual module, it reads from cssContentCache (line 237), which contains the unprocessed version. On initial hard page load, this raw inline <style> gets overridden by Vite's client-side CSS module system, which executes all transforms in the correct order. The problem only manifests during soft navigation.

    Introduced by the Environment API refactor (commit 141c4a26419, PR #14306). No comment or evidence that integration transform ordering was considered.

    Instrumentation Confirmation

    Debug logging confirmed the cssContentCache stores raw @apply directives and serves that same raw CSS in the HTML response:

    [TRANSFORM] code contains @apply: true → .custom{@apply p-3 bg-blue-500;}
    [LOAD] cached content contains @apply: true → .custom{@apply p-3 bg-blue-500;}
    

    Fix

    packages/astro/src/vite-plugin-css/index.ts:

    • Extracted the CSS caching transform into a new standalone plugin astro:dev-css-cache
    • Changed astroDevCssPlugin to return { plugins, cssCachePlugin } instead of a flat Plugin[] array
    • The cache plugin shares the same cssContentCache Map via closure

    packages/astro/src/core/create-vite.ts:

    • Registers devCss.plugins in the normal plugin position
    • Appends devCss.cssCachePlugin to the end of the plugin array after integration plugins have been merged, ensuring integration transforms (UnoCSS, etc.) run before caching

    packages/astro/test/0-css.test.ts:

    • Updated "resolves CSS from Vue" assertion from .vue-scoped{ to .vue-scoped[data-v- because the CSS cache now runs after Vue's scoped rewrite

    packages/astro/test/units/dev/css-cache-plugin-ordering.test.ts (new):

    • Verifies astroDevCssPlugin returns a separate cssCachePlugin not included in the main plugins array
    • Verifies the cache plugin's transform is present

    Verification

    Before fix: Server-rendered HTML contained raw @apply directives:

    <style>.custom[data-astro-cid-j6sxi7fa]{@apply p-3 bg-blue-500;}</style>

    After fix: Server-rendered HTML contains fully-resolved CSS:

    <style>.custom[data-astro-cid-j6sxi7fa]{padding:calc(var(--spacing) * 3);background-color:color-mix(...)}</style>

    Browser verification after soft navigation:

    • customBg: blue ✅ (was rgba(0,0,0,0))
    • applyColor: yellow ✅ (was rgb(0,0,0))
    • atApplyColor: red ✅ (was rgb(0,0,0))
    • customPadding: 12px ✅ (was 0px)

    All existing tests pass: 0-css.test.ts (38 pass), css-dynamic-import-dev.test.ts, view-transitions.test.ts, css-order*.test.ts, postcss.test.ts, tailwindcss.test.ts, scoped-style-strategy.test.ts, page-level-styles.test.ts, units/render/transitions.test.ts (26 pass), units/dev/css-cache-plugin-ordering.test.ts (2 pass, new).

    This report was made by an LLM. The analysis may be wrong, and the potential fix might not work, but is intended as a starting point for exploring the issue.

  13. added
    - P4: important
    and removed
    triage: needs triage
    on May 15, 2026
  14. matthewp commented on Jun 10, 2026

    @matthewp
    Contributor

    Fix was not tested, so closing. Please open a new issue if you still have this problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    - P3: minor bug- P4: importantpkg: astrotriage: fix pending

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions