Skip to content

Svelte components still don't always get styles when rendered conditionally #16251

@Snugug

Description

@Snugug

Astro Info

Astro                    v6.1.0
Vite                     v7.3.1
Node                     v24.11.1
System                   macOS (arm64)
Package Manager          pnpm
Output                   static
Adapter                  none
Integrations             @astrojs/svelte (v8.0.3)
                         nebula-cms (Local)

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

No response

Describe the Bug

This is a continuation of #14252. In NebulaCMS, I'm conditionally loading the actual editor form (https://github.com/Snugug/nebula-cms/blob/main/src/client/Admin.svelte#L233-L238) from a client:load component. In development, all of the CSS appears to load fine, but in production, the CSS for MetadataForm doesn't load and there's no errors in the console.

If helpful, I tried tracing this with an LLM, and the LLM suggests that this is the flow that's the problem:

  1. @sveltejs/vite-plugin-svelte sets cssScopeTo metadata on Svelte CSS virtual
  2. In the SSR build, Rollup tree-shakes conditionally-rendered components (behind {#if} blocks that don't execute during prerendering). Vite's CSS tree-shaking uses cssScopeTo to also remove their CSS from the SSR output
  3. But Astro's cssModuleToChunkIdMap still maps all CSS module IDs from the SSR chunk (they're present as modules, just content-empty)
  4. In the client build, allCssInSSR evaluates to true (all IDs mapped), so cssBuildPlugin deletes the client CSS asset from the bundle
  5. The cssScopeTo fix from PR Include styles for conditionally rendered Svelte 5 components #15227 adds the deleted CSS filename to pagesToCss, but inlineStylesheetsPlugin iterates Object.entries(bundle) — the asset was already deleted, so it's never processed
  6. Result: only SSR-rendered component styles make it to the final output

The LLM's suggested fix (internal t my project) is to override cssscopeTo via Vite plugin, which does appear to work, so it looks like it is at least related to that.

What's the expected result?

Svelte components that are rendered from NPM models, even if they're conditionally included in the code, should have their CSS available in a production build

Link to Minimal Reproducible Example

https://github.com/Snugug/nebula-cms/releases/tag/v0.1.5

Participation

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    - P4: importantViolate documented behavior or significantly impacts performance (priority)pkg: astroRelated to the core `astro` package (scope)pkg: svelteRelated to Svelte (scope)

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions