Chapter 01: Introduction to Astro Basics
- Understand Astro’s core concepts and advantages
- Master Astro project initialization and basic configuration
- Familiarize yourself with Astro file structure and routing system
- Learn 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 shipped to the client by default
- Flexibility: Supports multiple frontend frameworks (React, Vue, Svelte, Solid, etc.)
- Developer Experience: Powerful development tools and hot reload
- SEO Friendly: All pages are server-rendered by default
Traditional SPA (Single Page Application) frameworks ship large amounts of JavaScript code to the client, even for static content. Astro solves this problem by generating static HTML by default, only loading JavaScript when interactivity is needed.
Project Initialization
Creating a Project with create-astro
# Create new project with npm
npm create astro@latest my-astro-project
# Or with yarn
yarn create astro my-astro-project
# Or with pnpm
pnpm create astro my-astro-project
Project Template Selection
Astro provides several pre-built templates:
| Template Name | Description | Use Case |
|---|---|---|
minimal | Minimal template | Build from scratch |
blog | Blog template | Personal blog, technical docs |
portfolio | Portfolio template | Personal portfolio showcase |
docs | Documentation template | Technical documentation sites |
# Simulating 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 Explanations
- 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',
// Development 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 Process
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 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
Choose Astro for:
- Content-driven websites (blogs, documentation, marketing sites)
- Projects requiring excellent SEO
- Scenarios demanding high performance
- 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 for production
npm run build
# Preview build output
npm run preview
Summary
In this chapter, we learned the fundamentals of Astro, including:
- Astro’s Core Advantages: 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: How static site generation works
In the next chapter, we’ll dive deeper into Astro’s core features, including component syntax, Islands Architecture, and advanced usage of frontmatter.