Chapter 1 - Astro Basics
Chapter 1 - Astro Basics
Chapter 1: Astro Basics
- Understand the core concepts and advantages of Astro
- Master Astro project initialization and basic configuration
- Familiarize yourself with Astro file structure and routing system
- Understand how Static Site Generation (SSG) works
What is Astro
Astro is a modern static site generator designed for building fast, content-focused websites. It adopts a unique Islands Architecture pattern, allowing developers to add interactivity when needed while keeping most content static.
Core Advantages of Astro
- Performance First: No JavaScript sent to the client by default
- Flexibility: Supports multiple frontend frameworks (React, Vue, Svelte, Solid, etc.)
- Developer Experience: Provides powerful development tools and hot reloading
- SEO Friendly: All pages are server-side rendered by default
Traditional SPA (Single Page Application) frameworks send a lot of JavaScript code to the client, even for static content. Astro solves this problem by generating static HTML by default and only loading JavaScript when interactivity is needed.
Project Initialization
Creating a Project with create-astro
# Create a new project using npm
npm create astro@latest my-astro-project
# Or using yarn
yarn create astro my-astro-project
# Or using pnpm
pnpm create astro my-astro-project
Project Template Selection
Astro provides multiple pre-built templates:
| Template Name | Description | Use Cases |
|---|---|---|
minimal | Minimal template | Build from scratch |
blog | Blog template | Personal blog, technical documentation |
portfolio | Portfolio template | Personal portfolio display |
docs | Documentation template | Technical documentation sites |
# Simulate project initialization process
def create_astro_project(project_name, template="minimal"):
"""
Example function for creating an Astro project
Args:
project_name: Project name
template: Project template type
Returns:
dict: Project configuration information
"""
project_config = {
"name": project_name,
"template": template,
"dependencies": {
"astro": "^4.0.0",
"@astrojs/check": "^0.3.0",
"typescript": "^5.0.0"
},
"dev_server": {
"port": 4321,
"host": "localhost"
}
}
print(f"Creating Astro project: {project_name}")
print(f"Using template: {template}")
return project_config
# Example usage
project = create_astro_project("my-blog", "blog")
print(project)
Astro Project File Structure
Standard Project Structure
my-astro-project/
├── public/ # Static assets directory
│ ├── favicon.svg
│ └── robots.txt
├── src/ # Source code directory
│ ├── components/ # Components directory
│ │ └── Card.astro
│ ├── layouts/ # Layouts directory
│ │ └── Layout.astro
│ └── pages/ # Pages directory (file-based routing)
│ └── index.astro
├── astro.config.mjs # Astro configuration file
├── package.json
└── tsconfig.json
Key Directory Descriptions
- Files in the
src/pages/directory automatically become routes - File names determine URL paths
- Supports nested routes and dynamic routes
# Routing mapping examples
def astro_routing_examples():
"""
Astro file system routing examples
"""
route_mapping = {
# Static routes
"src/pages/index.astro": "/",
"src/pages/about.astro": "/about",
"src/pages/blog/index.astro": "/blog",
# Dynamic routes
"src/pages/blog/[slug].astro": "/blog/my-post",
"src/pages/users/[id].astro": "/users/123",
# Nested routes
"src/pages/blog/2023/[post].astro": "/blog/2023/my-post",
# Rest parameters
"src/pages/[...path].astro": "/any/nested/path"
}
print("Astro routing mapping rules:")
for file_path, url in route_mapping.items():
print(f"{file_path} -> {url}")
return route_mapping
# Example call
routing_examples = astro_routing_examples()
Astro Configuration File
Basic Configuration (astro.config.mjs)
import { defineConfig } from 'astro/config';
export default defineConfig({
// Site configuration
site: 'https://my-astro-site.com',
base: '/',
// Build configuration
outDir: './dist',
publicDir: './public',
// Dev server configuration
server: {
port: 4321,
host: true
},
// Integrations configuration
integrations: [],
// Vite configuration
vite: {
css: {
preprocessorOptions: {
scss: {
additionalData: `@import "src/styles/global.scss";`
}
}
}
}
});
Static Site Generation (SSG) Principles
Build-time Rendering Flow
SSG vs SSR vs SPA Comparison
| Feature | SSG (Astro) | SSR | SPA |
|---|---|---|---|
| Initial Load Speed | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐ |
| SEO Friendliness | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐ |
| Server Requirements | Static hosting | Node.js server | Static hosting |
| Build Time | Longer | None | Medium |
| Dynamic Content | Limited | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
Scenarios for choosing Astro:
- Content-driven websites (blogs, documentation, marketing sites)
- Projects requiring excellent SEO
- Scenarios with extremely high performance requirements
- Multi-person collaborative content management projects
Your First Astro Page
Creating a Simple Page
---
// src/pages/hello.astro
// Frontmatter - JavaScript executed at build time
const greeting = "Hello, Astro!";
const currentDate = new Date().toLocaleDateString();
---
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width" />
<title>Astro Hello Page</title>
</head>
<body>
<h1>{greeting}</h1>
<p>Today is: {currentDate}</p>
<!-- Inline styles -->
<style>
h1 {
color: #2563eb;
font-family: system-ui, sans-serif;
}
p {
color: #6b7280;
}
</style>
</body>
</html>
Running the Development Server
# Start development server
npm run dev
# Build production version
npm run build
# Preview build results
npm run preview
Summary
In this chapter, we learned the basics of Astro, including:
- Core Advantages of Astro: Performance-first, multi-framework support, SEO-friendly
- Project Initialization: Quickly create projects using create-astro
- File Structure: Understanding the file-based routing system
- Configuration Files: Basic configuration of astro.config.mjs
- SSG Principles: The working mechanism of static site generation
In the next chapter, we will dive deep into Astro’s core features, including component syntax, Islands Architecture, and advanced frontmatter usage.