🌌 Astro 项目总体结构概览#
一个典型的 Astro 项目目录大致如下:
my-astro-blog/
├── public/
├── src/
│ ├── assets/
│ ├── components/
│ ├── content/
│ ├── layouts/
│ ├── pages/
│ └── styles/
├── astro.config.mjs
├── package.json
├── tsconfig.json
└── README.mdplaintext下面我会一一解释这些目录在 Astro 的构建流程 中的作用。
🪐 1. public/ —— 静态资源(不被 Astro 处理)#
功能:这里的文件会“原样”复制到最终输出目录(默认 dist/)。
例子:
public/
├── favicon.svg
├── robots.txt
└── admin/
├── index.html
└── config.ymlplaintext特征:
-
不经过 Astro 编译;
-
可以直接通过
/路径访问(例如https://example.com/favicon.svg); -
适合放:
- 图标、logo
- 静态 HTML 页面(如 CMS 管理页)
- robots.txt、manifest.json 等配置文件
- 上传资源、图片(如 CMS 上传目录)
💫 2. src/pages/ —— 网页路由入口(核心)#
功能:这里的文件会被编译成独立页面(HTML 文件)。
路由规则: Astro 按照文件名自动生成路由:
| 文件 | 路由 |
|---|---|
src/pages/index.astro | / |
src/pages/about.astro | /about |
src/pages/blog/[slug].astro | /blog/some-article |
支持格式:
.astro:Astro 模板(推荐).md/.mdx:Markdown 文件(自动转换为页面).js/.ts:API endpoints(生成 JSON 或 server response)
🧩 3. src/components/ —— 可复用组件#
功能:这里放你定义的可复用 UI 单元,比如导航栏、页脚、卡片、文章预览框等。
特点:
- 可以用
.astro、.jsx、.tsx等写; - 在页面中以
<MyComponent />的方式引用; - 支持混合使用 React / Vue / Svelte / Solid 等框架的组件!
示例:
src/components/
├── Header.astro
├── Footer.astro
└── BlogCard.astroplaintext🧱 4. src/layouts/ —— 页面布局模板#
功能:定义页面的整体骨架(如导航栏 + 内容区 + 页脚)。
例子:
---
// src/layouts/BaseLayout.astro
const { title } = Astro.props;
---
<html>
<head>
<title>{title}</title>
</head>
<body>
<Header />
<slot /> <!-- 子页面内容插入点 -->
<Footer />
</body>
</html>astro然后在页面中使用:
---
import BaseLayout from "../layouts/BaseLayout.astro";
---
<BaseLayout title="About">
<h1>About Me</h1>
</BaseLayout>astro🧾 5. src/content/ —— 内容源(Astro Content Collections)#
Astro 内置内容集合系统,方便管理 Markdown / MDX 文章。
结构示例:
src/content/
└── posts/
├── first-post.md
├── second-post.md
└── config.ts ← 定义内容模式(schema)plaintext在 astro.config.mjs 里启用 @astro/content 集成后,Astro 会自动读取并验证这些内容。
适合写博客文章、项目介绍、作品集条目等。
🎨 6. src/styles/ —— 样式文件(CSS、SCSS、PostCSS)#
功能:集中存放全局样式。
例子:
src/styles/
├── global.css
└── markdown.cssplaintext你可以在 src/layouts/BaseLayout.astro 或 astro.config.mjs 中全局引入样式文件。
🧰 7. src/assets/ —— 被编译的资源(图片、字体等)#
与 public/ 不同:
- 这里的资源会经过 Astro/Vite 处理;
- 可以使用模块导入语法,如:
import logo from '../assets/logo.png';
<img src={logo} alt="logo" />astro构建时,Astro 会自动优化和 hash 命名这些资源。
🧭 8. 顶层配置文件#
| 文件 | 作用 |
|---|---|
astro.config.mjs | Astro 主配置文件:站点路径、集成插件、构建选项等 |
package.json | npm 项目配置:依赖、脚本命令 |
tsconfig.json | TypeScript 配置(如果你用 TS) |