文档
Gatsby Hello World — 静态博客站点
目标
创建一个 Gatsby 博客站点,展示 GraphQL 数据查询、静态生成和页面路由。
完整代码
项目初始化
gatsby new my-blog
cd my-blog
npm run develop # 访问 http://localhost:8000
首页 src/pages/index.js
import * as React from "react";
import { graphql, Link } from "gatsby";
// GraphQL 查询在构建时执行,结果注入 data prop
export const query = graphql`
query IndexPageQuery {
allMdx(sort: { frontmatter: { date: DESC } }) {
nodes {
id
frontmatter {
title
date(formatString: "YYYY-MM-DD")
description
}
fields { slug }
}
}
site {
siteMetadata {
title
description
}
}
}
`;
const IndexPage = ({ data }) => {
const posts = data.allMdx.nodes;
const { title: siteTitle, description } = data.site.siteMetadata;
return (
<main style={mainStyle}>
<h1>{siteTitle}</h1>
<p style={{ color: "#555" }}>{description}</p>
<h2>📝 最新文章</h2>
<ul style={{ listStyle: "none", padding: 0 }}>
{posts.map((post) => (
<li key={post.id} style={cardStyle}>
<Link to={post.fields.slug} style={{ textDecoration: "none", color: "#333" }}>
<h3 style={{ margin: 0 }}>{post.frontmatter.title}</h3>
<p style={{ color: "#666", fontSize: "0.9rem" }}>{post.frontmatter.description}</p>
<small style={{ color: "#999" }}>{post.frontmatter.date}</small>
</Link>
</li>
))}
</ul>
</main>
);
};
export default IndexPage;
const mainStyle = {
maxWidth: 680, margin: "40px auto", padding: "0 16px",
fontFamily: "Georgia, serif",
};
const cardStyle = {
padding: "20px 0", borderBottom: "1px solid #eee",
};
Gatsby 配置 gatsby-config.js
module.exports = {
siteMetadata: {
title: "我的技术博客",
description: "用 Gatsby 构建的静态博客",
siteUrl: "https://example.com",
},
plugins: [
"gatsby-plugin-image",
"gatsby-plugin-sharp",
{
resolve: "gatsby-source-filesystem",
options: { name: "posts", path: `${__dirname}/content/posts/` },
},
{
resolve: "gatsby-plugin-mdx",
options: { extensions: [".mdx", ".md"] },
},
],
};
文章模板 src/templates/blog-post.js
import * as React from "react";
import { graphql, Link } from "gatsby";
import { MDXRenderer } from "gatsby-plugin-mdx";
export const query = graphql`
query BlogPostQuery($slug: String!) {
mdx(fields: { slug: { eq: $slug } }) {
frontmatter {
title
date(formatString: "YYYY年MM月DD日")
description
}
body
}
}
`;
const BlogPost = ({ data }) => {
const { frontmatter, body } = data.mdx;
return (
<main style={{ maxWidth: 720, margin: "40px auto", padding: "0 16px" }}>
<Link to="/" style={{ color: "#6366f1" }}>← 返回首页</Link>
<h1>{frontmatter.title}</h1>
<p style={{ color: "#888" }}>{frontmatter.date}</p>
<article>
<MDXRenderer>{body}</MDXRenderer>
</article>
</main>
);
};
export default BlogPost;
示例 MDX 文章 content/posts/hello-world.mdx
---
title: "我的第一篇博客"
date: 2024-01-15
description: "使用 Gatsby 和 MDX 写博客就是这么简单"
---
# 你好,世界!
Gatsby 让静态博客变得简单而强大。
- ✅ **Markdown/MDX** 编写内容
- ✅ **GraphQL** 统一数据层
- ✅ **自动优化** 图片和性能
运行步骤
npm run develop # 开发模式,http://localhost:8000
npm run build # 构建生产版本到 public/
npm run serve # 预览生产构建
预期输出
- 首页显示文章列表(日期、标题、描述)
- 点击文章进入详情页,MDX 内容被渲染
- 所有页面均为纯静态 HTML
- GraphQL 浏览器:http://localhost:8000/___graphql 可交互式查询数据