🔥 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)
Astro Fundamentals••By Komal Nakrani

The Astro Compiler Explained: From .astro to JavaScript

The Astro compiler explained: how .astro files become JavaScript modules, how CSS is scoped with data-astro-cid, how scripts and islands are handled.

#Astro#Astro Compiler#Components#Vite#Scoped CSS

The Astro compiler turns each .astro file into a JavaScript module. The frontmatter becomes the body of a render function, the template becomes a tagged template literal that produces HTML, <style> blocks are scoped with a data-astro-cid-* attribute and split into separate CSS modules, <script> tags are pulled out for bundling, and any component with a client:* directive is recorded as an island. Vite then bundles that output like any other JavaScript.

In the Astro 7 line, the compiler is written in Rust and ships as @astrojs/compiler-rs with native Node.js bindings. Earlier Astro versions used a compiler written in Go and compiled to WebAssembly. The .astro syntax is the same either way.

Key Takeaways

  • Every .astro component compiles to a module whose default export is a component factory that renders HTML on the server.
  • Frontmatter code runs on the server (or at build time) inside that render function. None of it ships to the browser.
  • Styles are scoped by adding data-astro-cid-<hash> to elements and rewriting selectors to match. The strategy is configurable with scopedStyleStrategy.
  • The compiler records which imported components are hydrated and with which directive, so Astro knows exactly which JavaScript each page needs.
  • Template syntax errors (unclosed tags, invalid expressions) come from the compiler, before Vite or your code runs.

Where the compiler fits

When Vite needs a .astro file, Astro’s vite-plugin-astro reads the source and calls the compiler’s transform() function. The compiler returns:

  • code: the JavaScript module.
  • css: an array of scoped CSS strings, one per <style> block.
  • scripts: the component’s <script> blocks.
  • hydratedComponents and clientOnlyComponents: components used with client:* directives.
  • diagnostics: errors and warnings with positions in the original file.

Vite then treats the module as normal JavaScript and the CSS and scripts as separate virtual modules. The compiler does no bundling and no type checking; it’s a translator from one syntax to another. The How Astro uses Vite explainer covers the layer around it.

What the output looks like

Take this component:

---
// src/components/Card.astro
import Counter from './Counter.jsx';
const { title } = Astro.props;
---
<h1>{title}</h1>
<Counter client:visible start={1} />
<style>h1 { color: red; }</style>

Running it through @astrojs/compiler-rs with Astro’s default scoping produces this (lightly trimmed):

// Compiled output of Card.astro
import { render as $$render, createAstro as $$createAstro, createComponent as $$createComponent,
  renderComponent as $$renderComponent, maybeRenderHead as $$maybeRenderHead,
  createMetadata as $$createMetadata } from "astro/runtime/server/index.js";
import Counter from "./Counter.jsx";
import "/src/components/Card.astro?astro&type=style&index=0&lang.css";
import * as $$module1 from "./Counter.jsx";

export const $$metadata = $$createMetadata("/src/components/Card.astro", {
  modules: [{ module: $$module1, specifier: "./Counter.jsx", assert: {} }],
  hydratedComponents: [Counter],
  clientOnlyComponents: [],
  hydrationDirectives: new Set(["visible"]),
  hoisted: []
});

const $$Card = $$createComponent(($$result, $$props, $$slots) => {
  const Astro = $$result.createAstro($$props, $$slots);
  Astro.self = $$Card;
  const { title } = Astro.props;
  return $$render`${$$maybeRenderHead($$result)}<h1 data-astro-cid-7igagzy5>${title}</h1>
${$$renderComponent($$result, "Counter", Counter, {
    "client:visible": true,
    "start": 1,
    "data-astro-cid-7igagzy5": true,
    "client:component-hydration": "visible",
    "client:component-path": "./Counter.jsx",
    "client:component-export": "default"
  })}`;
}, "/src/components/Card.astro", undefined);

export default $$Card;

And the CSS output:

/* Card.astro?astro&type=style&index=0&lang.css */
h1[data-astro-cid-7igagzy5] {
  color: red;
}

Every part of the .astro file has a clear destination. The rest of this article walks through them.

Frontmatter becomes the render function

The code between the --- fences is placed inside the function passed to $$createComponent. Imports are hoisted to the top of the module, as JavaScript requires, but everything else runs each time the component renders.

That has practical consequences:

  • Frontmatter runs on the server only. In a static build that means once per page at build time; with on-demand rendering, once per request. It never runs in the browser, so secrets and database calls are safe there.
  • Astro is per-render. $$result.createAstro($$props, $$slots) creates a fresh Astro object with that render’s props, slots, URL and request. That’s why Astro.props can differ between two uses of the same component on one page.
  • Top-level await works. The render function is async, so const data = await fetch(...) in frontmatter is fine.
  • Module-level code runs once. Imports, and anything in the imported modules, run once per build or server start. Put expensive shared work (loading a large JSON file, for instance) in a separate module to take advantage of that.

The template becomes a tagged template literal

The HTML part becomes a template literal tagged with $$render. Static HTML is kept as strings; each {expression} becomes a ${...} slot. At render time, Astro’s runtime walks the template, escapes expression values (so {userInput} can’t inject HTML), awaits promises, and streams the result.

Components in the template become $$renderComponent calls with their props as an object. Slots become functions passed alongside. $$maybeRenderHead marks the first point where Astro can safely insert the <head> contents (styles and scripts collected from every component on the page) if the page didn’t render a <head> explicitly.

Because the template is compiled to strings plus expressions, there’s no virtual DOM and no diffing. Rendering an Astro component is string concatenation with escaping, which is why it’s fast and why the output is plain HTML.

Directives the compiler handles

Template directives are compile-time instructions:

Directive What the compiler does
class:list Converts to a call that joins and dedupes class names
set:html Inserts the value without escaping
set:text Inserts the value as escaped text
define:vars Passes frontmatter values into a <style> or <script>
is:inline Leaves a <script> or <style> in place, unprocessed
is:global Skips scoping for a <style> block
client:* Records the component as an island and adds hydration metadata
server:defer Marks a component as a Server Island

The template syntax cheatsheet lists every directive with examples.

How CSS scoping works

The compiler computes a short hash for the component (7igagzy5 above), then:

  1. Adds a data-astro-cid-7igagzy5 attribute to every HTML element in the template.
  2. Rewrites every selector in the component’s <style> blocks to require that attribute: h1 becomes h1[data-astro-cid-7igagzy5].
  3. Passes the attribute to child components as a prop, so a component’s root element can opt into its parent’s styles.

The result: styles in Card.astro apply only to elements Card.astro rendered. Two components can both style h1 without conflict.

The strategy is configurable:

// astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  scopedStyleStrategy: 'attribute', // default: h1[data-astro-cid-xxx]
  // 'class' -> h1.astro-xxx    (adds a class instead of an attribute)
  // 'where' -> h1:where(.astro-xxx) (zero added specificity)
});

'where' keeps selector specificity identical to what you wrote, which helps when global styles need to override component styles. 'class' and 'attribute' add one class-level of specificity.

To escape scoping, use <style is:global> for a whole block or :global(.selector) for one selector. The scoped vs global styles guide covers when to use which.

How scripts are handled

A plain <script> in an .astro file is extracted by the compiler and referenced as a virtual module (Card.astro?astro&type=script&index=0&lang.ts). Vite then bundles it as a TypeScript module: imports resolve, it’s minified, and it’s deduplicated, so a component used ten times on a page includes its script once.

Add any attribute other than src (such as is:inline, type="module" or data-*) and the compiler leaves the script exactly where it is, unprocessed. That’s the escape hatch for analytics snippets and JSON-LD.

How islands are marked

When the compiler sees <Counter client:visible />, it does three things:

  1. Adds the component to hydratedComponents in $$metadata, and its directive to hydrationDirectives.
  2. Adds hidden props to the render call: client:component-path, client:component-export and client:component-hydration.
  3. Leaves the actual rendering to the runtime, which renders the component to HTML on the server and wraps it in an <astro-island> element with the URLs needed to load and hydrate it.

During the build, Astro reads that metadata to create one client chunk per hydrated component, and adds only the needed directive scripts (here, the visible loader) to pages that use it. That’s the mechanism behind “zero JavaScript by default”: if no component on a page is in hydratedComponents, the page gets no island JavaScript. The hydration explainer follows what happens next in the browser.

Errors that come from the compiler

Compiler errors appear before any of your code runs, with a position in the .astro file. Common ones:

  • Unclosed or mismatched tags. <div><p></div> fails to parse.
  • Invalid expressions. A JavaScript syntax error inside {...}.
  • Unescaped { in text. Literal braces in the template are read as expressions; write {'{'} or put them in a code element.
  • Multiple frontmatter fences or code before the first ---.

If the error points to a line in your .astro file with a message about parsing or unexpected tokens, it’s the compiler. If it mentions imports or modules, it’s Vite. If it happens while rendering a specific page, it’s your code at runtime.

Editor tooling

Your editor doesn’t run the compiler’s JavaScript output for type checking. The Astro language server (behind the VS Code extension and astro check) converts .astro files to a TSX representation that TypeScript understands, which is how you get autocompletion for Astro.props and type errors in templates. It’s a different output from the same source.

Komal themes are ordinary Astro 7 components that go through this compiler like any other project, so opening one is a good way to see the patterns in real files; browse Astro themes or read the folder structure docs for where components live. The source for the compiler is in the withastro GitHub organization, and the Astro components docs describe the syntax it accepts.

FAQ

What does the Astro compiler do?

It converts .astro components into JavaScript modules that render HTML on the server, scopes component CSS, extracts scripts for bundling and records which child components need to hydrate in the browser.

What language is the Astro compiler written in?

The compiler used by Astro 7 is written in Rust and published as @astrojs/compiler-rs with native Node.js bindings. Earlier versions of Astro used a compiler written in Go and compiled to WebAssembly.

How does Astro scope CSS?

The compiler adds a data-astro-cid-<hash> attribute to each element in a component and rewrites the component’s selectors to require it. You can switch to class-based or :where() scoping with the scopedStyleStrategy option.

Does frontmatter code run in the browser?

No. Frontmatter is compiled into the server-side render function. It runs at build time for static pages or per request for on-demand pages, and none of it is sent to the browser.

Why does Astro say my template has an unexpected token?

The compiler found something it can’t parse, most often an unclosed tag, a JavaScript syntax error inside braces, or a literal brace character in text. Check the line it reports in the .astro file.