Chapter 01: Introduction to Astro Basics

Haiyue
8min
Learning Objectives
  • 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.

🔄 正在渲染 Mermaid 图表...

Core Advantages of Astro

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

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 NameDescriptionUse Case
minimalMinimal templateBuild from scratch
blogBlog templatePersonal blog, technical docs
portfolioPortfolio templatePersonal portfolio showcase
docsDocumentation templateTechnical 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

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',

  // 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

🔄 正在渲染 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

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:

  1. Astro’s Core Advantages: 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: How static site generation works
Next Steps

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