🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Performance••By Komal Nakrani

Astro Assets: How Astro Processes CSS, JS and Images

How Astro processes assets: scoped and global CSS, stylesheet inlining, script bundling, is:inline, image optimization, and what ends up in dist/_astro.

#Astro#Assets#CSS#Images#Build

Astro processes assets with Vite during astro build: CSS from <style> tags and imports is scoped, bundled, minified and either inlined or written to hashed files in dist/_astro/; <script> tags are bundled as ES modules; images imported from src/ are optimized by the <Image /> component; and everything in public/ is copied unchanged. Knowing which path an asset takes tells you how it’s cached, whether it’s optimized, and how to reference it.

This explainer walks through each type of Astro asset in Astro 7, with the config options that change the defaults.

Key Takeaways

  • Files in src/ are processed and fingerprinted; files in public/ are copied as-is.
  • Processed assets land in dist/_astro/ with content hashes, so they can be cached forever.
  • Component <style> is scoped by default; stylesheets under 4 kB are inlined (build.inlineStylesheets: 'auto').
  • <script> tags are bundled as modules and deduplicated; is:inline opts out of processing.
  • Images imported from src/ get dimensions, format conversion and responsive sizes through <Image />.

The two asset paths: src and public

Every asset in an Astro project goes one of two ways:

src/ (processed) public/ (unprocessed)
How you reference it import in frontmatter, or relative path in Markdown Absolute URL like /favicon.svg
Build step Bundled, minified, optimized by Vite and Astro Copied byte for byte
Output location dist/_astro/name.hash.ext Same path under dist/
File name Content-hashed Unchanged
Missing file Build error 404 at runtime
Good for CSS, scripts, images, fonts used by components robots.txt, favicons, CNAME, files that need a fixed URL

The hash in processed file names changes whenever the content changes. That’s what lets a host cache /_astro/ files for a year: a new deploy produces new URLs, so visitors never see stale assets. The Astro caching explainer covers the headers to set.

How Astro processes CSS

Scoped styles in components

A <style> tag in an .astro component is scoped to that component by default. Astro adds a data-astro-cid-* attribute to the component’s elements and rewrites selectors to match:

---
// src/components/Card.astro
---
<article class="card"><slot /></article>

<style>
  .card { padding: 1.5rem; border-radius: 0.75rem; }
</style>

The output CSS targets .card[data-astro-cid-abc123], so .card in another component isn’t affected. The scopedStyleStrategy config option switches to class-based scoping ('class') or :where() selectors ('where') if you need different specificity. Add is:global to a <style> tag to skip scoping. The scoped vs global styles guide covers when to use each.

Imported stylesheets

CSS imported in frontmatter (import '../styles/global.css') or from npm packages is processed the same way, without scoping. Vite runs PostCSS (and Tailwind CSS, if configured), and preprocessors like Sass work once their package is installed.

Bundling and code splitting

During the build, Astro collects the CSS each page uses and splits it into chunks. CSS shared by many pages goes into a common file, and page-specific CSS stays separate, so each page loads only the styles it renders. Everything is minified.

Inlining small stylesheets

The build.inlineStylesheets option decides whether CSS is linked or inlined in <style> tags:

Value Behavior
'auto' (default) Inline stylesheets smaller than Vite’s assetsInlineLimit (4 kB by default); link larger ones
'always' Inline all project CSS, removing render-blocking requests
'never' Always link external files, maximizing cache reuse across pages
// astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  build: { inlineStylesheets: 'always' },
});

Inlining saves a request on first load; linking lets repeat visitors reuse the cached file. 'auto' is a sensible middle ground for most sites. The inline critical CSS tip goes further.

How Astro processes JavaScript

Processed scripts

A plain <script> tag in an .astro component is processed by default:

---
// src/components/MenuToggle.astro
---
<button class="menu-toggle" aria-expanded="false">Menu</button>

<script>
  import { toggle } from '../lib/menu';
  document.querySelectorAll('.menu-toggle').forEach((button) => {
    button.addEventListener('click', () => toggle(button));
  });
</script>

Astro and Vite then:

  1. Bundle the script with its imports (npm packages and local modules work).
  2. Compile TypeScript, so you can write typed code in the tag.
  3. Output it as type="module", which is deferred and doesn’t block rendering.
  4. Deduplicate it: a component used 20 times on a page includes its script once.
  5. Minify it, inlining very small scripts and writing larger ones to dist/_astro/.

Inline scripts

is:inline turns processing off. The script is written exactly as you wrote it, every time the component renders, with no bundling, imports or TypeScript:

<script is:inline>
  // Runs before paint to avoid a flash of the wrong theme
  document.documentElement.dataset.theme = localStorage.getItem('theme') ?? 'light';
</script>

Use it for tiny scripts that must run immediately in the <head>, for third-party snippets, or for files in public/. Passing frontmatter values into a script with define:vars also makes it inline; see the define:vars tip.

Framework islands

React, Vue, Svelte and other framework components with a client:* directive are bundled separately, with shared framework runtime chunks. Each island’s JavaScript loads according to its directive: immediately, on idle, when visible, or on a media query. Components without a directive render to HTML with no JavaScript at all. The client directive guide compares them, and the bundle size analysis tip shows how to see what each page ships.

How Astro processes images

Images get the most work, because they’re usually the largest bytes on a page.

---
// src/components/Hero.astro
import { Image } from 'astro:assets';
import hero from '../assets/hero.jpg';
---
<Image src={hero} alt="A team reviewing a site design" width={1200} priority />

When you import an image from src/, Astro reads its dimensions and format at build time. <Image /> then:

  • Converts it to WebP by default (configurable with format).
  • Resizes it to the requested width, and can generate srcset sizes for responsive layouts.
  • Adds width and height attributes, which prevents layout shift.
  • Sets loading="lazy" and decoding="async" unless you set priority, which loads it eagerly with high fetch priority for above-the-fold images.
  • Writes the result to dist/_astro/ with a hashed file name.

<Picture /> outputs several formats (for example AVIF and WebP) with fallbacks. Remote images can be optimized too once their domain is allowed in image.domains or image.remotePatterns. Images in Markdown referenced with relative paths (![Alt](./photo.jpg)) are processed the same way. Images in public/ are never optimized. The Image component guide covers every option, and the image cheatsheet is a quick reference.

SVG files imported from src/ can be used as components (import Logo from '../assets/logo.svg'), which inlines the SVG markup and lets you pass attributes like width and class.

Fonts and other files

Font files referenced from CSS in src/ (via url()) are processed and hashed like images. Astro’s Fonts API, configured with fonts in astro.config.mjs and the <Font /> component from astro:assets, downloads font files from providers or local paths, serves them from your own site, and can generate preload links and fallback metrics. Other imports, such as JSON, are bundled into the JavaScript that uses them, or read at build time in frontmatter and never shipped.

What the build output looks like

After npm run build, a small site’s output looks like this:

dist/
├── _astro/
│   ├── index.DxQ2kP1a.css
│   ├── hero.CmT8fW3e_Z1abc.webp
│   ├── MenuToggle.astro_astro_type_script_index_0_lang.Bf3kL9.js
│   └── client.Ab12Cd.js
├── blog/
│   └── hello/index.html
├── favicon.svg
├── robots.txt
└── index.html

Everything in _astro/ is fingerprinted and safe to cache long term. Everything else comes from your pages or public/. The folder name can be changed with build.assets, and build.assetsPrefix serves the _astro/ files from a separate CDN domain. HTML whitespace is collapsed by default (compressHTML uses JSX-style rules since Astro 7).

Common Astro asset mistakes

Mistake Effect Fix
Putting content images in public/ No optimization, no dimensions, no hashing Move them to src/assets/ and use <Image />
Referencing src/ files by URL (/src/assets/a.jpg) Works in dev, 404 in production Import the file instead
Using is:inline for normal component scripts No bundling, duplicated per use Remove is:inline
Large global CSS imported in every layout Every page loads all styles Keep component styles in components
Hero image lazy-loaded Slower largest contentful paint Add priority to the above-the-fold image

Komal themes follow the src/ path for components, styles and images, so a production build already produces hashed, optimized assets; you can inspect the output by building any Astro theme locally. The styling docs cover where theme styles live. For the official details, see Astro’s images guide and scripts guide.

FAQ

What is the difference between the src and public folders for Astro assets?

Files in src/ are imported and processed: bundled, optimized and given hashed file names in dist/_astro/. Files in public/ are copied unchanged to the root of dist/ and referenced by absolute URL.

Does Astro bundle CSS automatically?

Yes. Astro collects CSS from component <style> tags and imports, minifies it, splits it per page, and either inlines it or links it as hashed files, depending on build.inlineStylesheets.

What does is:inline do in Astro?

It tells Astro not to process a <script> or <style> tag. The tag is output exactly as written, without bundling, TypeScript compilation, scoping or deduplication.

Does Astro optimize images automatically?

Images imported from src/ and rendered with <Image /> or <Picture /> are resized, converted to modern formats and given dimensions. Plain <img> tags pointing at public/ files aren’t optimized.

Where does Astro put built assets?

Processed assets go to dist/_astro/ with content hashes in their names. You can rename the folder with build.assets or serve it from a CDN with build.assetsPrefix.