Astro Framework Getting Started Guide
Deep dive into Astro, a modern static site generator, and learn how to use it to build high-performance websites.
---
Astro framework introduction
Astro Framework Getting Started Guide
Astro is a modern static site generator designed for building fast, content-focused websites. This article will introduce you to Astro’s core concepts and usage methods.
What is Astro?
Astro is a brand new static site building tool that combines modern developer experience with optimized performance. Its core philosophy is:
- Zero JavaScript by default - Ships zero JavaScript to the browser by default
- Component Islands - Only interactive components load JavaScript
- Framework agnostic - Supports React, Vue, Svelte, and other frameworks
Core Features
1. Performance First
// Astro only ships necessary JavaScript
export default function Counter() {
// This code only runs on the server
console.log('Server-side log');
return (
<div>Static content, no JavaScript needed</div>
);
}
2. Islands Architecture
---
// Server-side code
const data = await fetch('/api/data').then(r => r.json());
---
<div>
<!-- Static content -->
<h1>{data.title}</h1>
<!-- Interactive component islands -->
<Counter client:load />
<SearchBox client:visible />
</div>
3. Content Collections
// src/content/config.ts
import { defineCollection, z } from 'astro:content';
const blogCollection = defineCollection({
type: 'content',
schema: z.object({
title: z.string(),
description: z.string(),
publishDate: z.date(),
tags: z.array(z.string()),
}),
});
export const collections = {
blog: blogCollection,
};
Project Structure
src/
├── components/ # Reusable components
│ ├── Header.astro
│ └── Footer.astro
├── layouts/ # Page layouts
│ └── Layout.astro
├── pages/ # Page routes
│ ├── index.astro
│ └── blog/
│ └── [slug].astro
├── content/ # Content collections
│ └── blog/
│ └── post-1.md
└── styles/ # Style files
└── global.css
Getting Started
1. Create New Project
npm create astro@latest my-blog
cd my-blog
npm install
npm run dev
2. Create Your First Page
---
// src/pages/about.astro
const title = "About Us";
---
<html lang="en">
<head>
<title>{title}</title>
</head>
<body>
<h1>{title}</h1>
<p>This is the about page content.</p>
</body>
</html>
3. Add Styles
---
// Component script
---
<div class="container">
<h1>Title</h1>
<p>Content</p>
</div>
<style>
.container {
max-width: 800px;
margin: 0 auto;
padding: 2rem;
}
h1 {
color: #2563eb;
font-size: 2.5rem;
}
</style>
Advanced Features
1. Client Directives
Astro provides various client directives to control component hydration timing:
<!-- Load immediately -->
<Component client:load />
<!-- Load when page is idle -->
<Component client:idle />
<!-- Load when component is visible -->
<Component client:visible />
<!-- Load when media query matches -->
<Component client:media="(max-width: 768px)" />
2. Content Collections API
// Get all blog posts
const posts = await getCollection('blog');
// Filter drafts
const publishedPosts = await getCollection('blog', ({ data }) => {
return !data.draft;
});
// Sort by date
const sortedPosts = posts.sort(
(a, b) => b.data.publishDate.valueOf() - a.data.publishDate.valueOf()
);
3. Dynamic Routes
---
// src/pages/blog/[slug].astro
export async function getStaticPaths() {
const posts = await getCollection('blog');
return posts.map((post) => ({
params: { slug: post.slug },
props: { post },
}));
}
const { post } = Astro.props;
const { Content } = await post.render();
---
<Layout>
<h1>{post.data.title}</h1>
<Content />
</Layout>
Performance Optimization
1. Image Optimization
---
import { Image } from 'astro:assets';
import heroImage from '../assets/hero.jpg';
---
<Image
src={heroImage}
alt="Hero image"
width={800}
height={400}
format="webp"
quality={80}
/>
2. Prefetch Links
<a href="/blog/" data-astro-prefetch>
Blog
</a>
3. View Transitions
---
import { ViewTransitions } from 'astro:transitions';
---
<html>
<head>
<ViewTransitions />
</head>
<body>
<!-- Page content -->
</body>
</html>
Deployment
Vercel
npm run build
# Auto-deploy to Vercel
Netlify
# netlify.toml
[build]
command = "npm run build"
publish = "dist"
GitHub Pages
# .github/workflows/deploy.yml
name: Deploy to GitHub Pages
on:
push:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 18
- run: npm install
- run: npm run build
- uses: actions/upload-pages-artifact@v1
with:
path: ./dist
Common Questions
Q: How to add interactive functionality?
A: Use client directives with supported framework components:
---
import ReactCounter from '../components/Counter.jsx';
---
<ReactCounter client:load />
Q: How to handle styles?
A: Astro supports multiple styling approaches:
- Component-level
<style>tags - Global CSS files
- CSS preprocessors (Sass, Less)
- CSS-in-JS libraries
- Tailwind CSS
Q: How to optimize SEO?
A: Use Astro’s SEO best practices:
---
const { title, description } = Astro.props;
---
<head>
<title>{title}</title>
<meta name="description" content={description} />
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
</head>
Conclusion
Astro is a powerful modern static site generator that combines excellent developer experience with outstanding performance. Through this guide, you should now understand:
- Astro’s core concepts and features
- Basic project structure and syntax
- How to use advanced features
- Performance optimization techniques
- Deployment options
Start your Astro journey! Whether it’s a personal blog or corporate website, Astro provides excellent solutions for you.