Chapter 1 - Astro Basics

Chapter 1 - Astro Basics

Haiyue
8min

Chapter 1: Astro Basics

Learning Objectives
  • 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

a2=areaa^2 = area

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.

🔄 正在渲染 Mermaid 图表...

Core Advantages of Astro

  1. Performance First: No JavaScript sent to the client by default
  2. Flexibility: Supports multiple frontend frameworks (React, Vue, Svelte, Solid, etc.)
  3. Developer Experience: Provides powerful development tools and hot reloading
  4. SEO Friendly: All pages are server-side rendered by default
Why Choose Astro

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 NameDescriptionUse Cases
minimalMinimal templateBuild from scratch
blogBlog templatePersonal blog, technical documentation
portfolioPortfolio templatePersonal portfolio display
docsDocumentation templateTechnical 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

Important Conventions
  • 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

🔄 正在渲染 Mermaid 图表...

SSG vs SSR vs SPA Comparison

FeatureSSG (Astro)SSRSPA
Initial Load Speed⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
SEO Friendliness⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
Server RequirementsStatic hostingNode.js serverStatic hosting
Build TimeLongerNoneMedium
Dynamic ContentLimited⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
Best Practices

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:

  1. Core Advantages of Astro: Performance-first, multi-framework support, SEO-friendly
  2. Project Initialization: Quickly create projects using create-astro
  3. File Structure: Understanding the file-based routing system
  4. Configuration Files: Basic configuration of astro.config.mjs
  5. SSG Principles: The working mechanism of static site generation
Next Steps

In the next chapter, we will dive deep into Astro’s core features, including component syntax, Islands Architecture, and advanced frontmatter usage.