#Astro loading in too many css files

4 messages · Page 1 of 1 (latest)

dry flame
#

Why would astro be loading in all my component.module.css files when I'm not importing all my components to the page?

dull larkBOT
#

Hi @dry flame. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

This is a known behavior in Astro related to how its build process works with the module graph.

Even if a component is not displayed in the final output (e.g., it's conditionally rendered and the condition is false), once it is imported in your component/page file, Astro will process, optimize, and bundle its <style> tag or associated CSS module. [unexpected style]

There's also another important gotcha: imported CSS can "leak". If you import a component that itself imports a CSS file, that CSS will be applied even if the component is never actually used or rendered on the page. [import order]

For example:

---
import "./make-it-green.css"
import PurpleComponent from "./PurpleComponent.astro"; // imports make-it-purple.css internally
---
<!-- PurpleComponent is never used here, but its CSS is still loaded -->

What you can do

  • Only import components you actually need on a given page. If a component and its CSS are not imported, they won't be included.
  • If you're using conditional rendering (e.g., {condition && <MyComponent />}), be aware that simply having the import statement at the top of the file is enough for Astro to include that component's CSS — regardless of whether the component renders.

In short, the trigger for CSS inclusion is the import statement, not whether the component actually renders in the output.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@dry flame Kapa.ai is still learning and improving, please let me know how I did by reacting below.