跳转到主内容
技术 #Astro #前端 #静态站点 #Web开发

Astro 框架入门指南

深入了解 Astro 这个现代化的静态站点生成器,学习如何使用它构建高性能的网站。

作者: 作者
6 分钟阅读
Astro 框架介绍 ---

Astro 框架介绍

Astro 框架入门指南

Astro 是一个现代化的静态站点生成器,它专为构建快速、以内容为中心的网站而设计。本文将带你了解 Astro 的核心概念和使用方法。

什么是 Astro?

Astro 是一个全新的静态站点构建工具,它将现代开发者体验与优化的性能相结合。它的核心理念是:

  • 零 JavaScript 默认 - 默认情况下发送零 JavaScript 到浏览器
  • 组件岛屿 - 只有需要交互的组件才会加载 JavaScript
  • 框架无关 - 支持 React、Vue、Svelte 等多种框架

核心特性

1. 性能优先

// Astro 只发送必要的 JavaScript
export default function Counter() {
  // 这段代码只在服务器运行
  console.log('服务器端日志');
  
  return (
    <div>静态内容,无需 JavaScript</div>
  );
}

2. 组件岛屿架构

---
// 服务器端代码
const data = await fetch('/api/data').then(r => r.json());
---

<div>
  <!-- 静态内容 -->
  <h1>{data.title}</h1>
  
  <!-- 交互式组件岛屿 -->
  <Counter client:load />
  <SearchBox client:visible />
</div>

3. 内容集合

// 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,
};

项目结构

src/
├── components/          # 可复用组件
│   ├── Header.astro
│   └── Footer.astro
├── layouts/            # 页面布局
│   └── Layout.astro
├── pages/              # 页面路由
│   ├── index.astro
│   └── blog/
│       └── [slug].astro
├── content/            # 内容集合
│   └── blog/
│       └── post-1.md
└── styles/             # 样式文件
    └── global.css

开始使用

1. 创建新项目

npm create astro@latest my-blog
cd my-blog
npm install
npm run dev

2. 创建第一个页面

---
// src/pages/about.astro
const title = "关于我们";
---

<html lang="zh">
  <head>
    <title>{title}</title>
  </head>
  <body>
    <h1>{title}</h1>
    <p>这是关于页面的内容。</p>
  </body>
</html>

3. 添加样式

---
// 组件脚本
---

<div class="container">
  <h1>标题</h1>
  <p>内容</p>
</div>

<style>
  .container {
    max-width: 800px;
    margin: 0 auto;
    padding: 2rem;
  }
  
  h1 {
    color: #2563eb;
    font-size: 2.5rem;
  }
</style>

高级功能

1. 客户端指令

Astro 提供多种客户端指令来控制组件的水合时机:

<!-- 立即加载 -->
<Component client:load />

<!-- 页面空闲时加载 -->
<Component client:idle />

<!-- 组件可见时加载 -->
<Component client:visible />

<!-- 媒体查询匹配时加载 -->
<Component client:media="(max-width: 768px)" />

2. 内容集合 API

// 获取所有博客文章
const posts = await getCollection('blog');

// 过滤草稿
const publishedPosts = await getCollection('blog', ({ data }) => {
  return !data.draft;
});

// 按日期排序
const sortedPosts = posts.sort(
  (a, b) => b.data.publishDate.valueOf() - a.data.publishDate.valueOf()
);

3. 动态路由

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

性能优化

1. 图片优化

---
import { Image } from 'astro:assets';
import heroImage from '../assets/hero.jpg';
---

<Image
  src={heroImage}
  alt="Hero 图片"
  width={800}
  height={400}
  format="webp"
  quality={80}
/>

2. 预获取链接

<a href="/blog/" data-astro-prefetch>
  博客
</a>

3. 视图过渡

---
import { ViewTransitions } from 'astro:transitions';
---

<html>
  <head>
    <ViewTransitions />
  </head>
  <body>
    <!-- 页面内容 -->
  </body>
</html>

部署

Vercel

npm run build
# 自动部署到 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

常见问题

Q: 如何添加交互功能?

A: 使用客户端指令和支持的框架组件:

---
import ReactCounter from '../components/Counter.jsx';
---

<ReactCounter client:load />

Q: 如何处理样式?

A: Astro 支持多种样式方案:

  • 组件级 <style> 标签
  • 全局 CSS 文件
  • CSS 预处理器(Sass、Less)
  • CSS-in-JS 库
  • Tailwind CSS

Q: 如何优化 SEO?

A: 使用 Astro 的 SEO 最佳实践:

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

总结

Astro 是一个强大的现代化静态站点生成器,它结合了优秀的开发者体验和出色的性能表现。通过本指南,你应该已经掌握了:

  1. Astro 的核心概念和特性
  2. 基本的项目结构和语法
  3. 高级功能的使用方法
  4. 性能优化技巧
  5. 部署选项

开始你的 Astro 之旅吧!无论是个人博客还是企业网站,Astro 都能为你提供出色的解决方案。