入门教程 - 从数据到静态站点

知识库
知识库文档
/tech-stacks/gatsby/tutorial/入门教程 - 从数据到静态站点.md

文档

Gatsby 入门教程:从数据到静态站点

一、Gatsby 是什么?

Gatsby 是一个基于 React 的静态站点生成器(SSG)。它的核心创新是 GraphQL 数据层——在构建时从任何来源(Markdown、CMS、API、数据库)拉取数据,生成纯静态 HTML/CSS/JS。曾是 JAMStack 运动的标杆,虽然近年被 Next.js 和 Astro 分流,但在内容密集型网站(文档站、营销站、博客)领域仍有大量用户。

核心概念

构建阶段:
  [数据源] → GraphQL 数据层 → React 组件 → 静态 HTML 页面
  (CMS/MDX/API)    (统一查询)        (模板渲染)       (输出到 public/)
  • Source Plugin:从数据源拉取数据到 GraphQL 层(如 gatsby-source-filesystem
  • Transformer Plugin:转换数据格式(如 gatsby-plugin-mdx 将 MDX 转为可查询节点)
  • Template:为每种数据类型指定渲染模板
  • gatsby-node.js:编程式创建页面

二、数据层详解

GraphQL 查询模式

http://localhost:8000/___graphql 可以交互式探索所有可用数据:

# 页面组件中用这种查询
query {
  site {
    siteMetadata { title }
  }
  allFile {
    nodes { name, extension }
  }
  allMdx {
    nodes {
      frontmatter { title, date }
      excerpt
    }
  }
}

# 非页面组件用 useStaticQuery hook
const data = useStaticQuery(graphql`
  query {
    site { siteMetadata { title } }
  }
`);

三、编程式创建页面

gatsby-node.js 中:

exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions;

  const result = await graphql(`
    query {
      allMdx {
        nodes {
          id
          fields { slug }
        }
      }
    }
  `);

  // 为每篇文章创建一个页面
  result.data.allMdx.nodes.forEach((node) => {
    createPage({
      path: node.fields.slug,
      component: path.resolve("./src/templates/blog-post.js"),
      context: { id: node.id }, // 传给模板的变量
    });
  });
};

// 为 Markdown 文件自动生成 slug
exports.onCreateNode = ({ node, actions }) => {
  const { createNodeField } = actions;
  if (node.internal.type === "Mdx") {
    const slug = "/posts/" + node.frontmatter.title
      .toLowerCase().replace(/\s+/g, "-");
    createNodeField({ node, name: "slug", value: slug });
  }
};

四、图片优化

Gatsby 的图片处理是杀手级特性:

import { GatsbyImage, getImage } from "gatsby-plugin-image";

// 查询
export const query = graphql`
  query {
    file(relativePath: { eq: "hero.jpg" }) {
      childImageSharp {
        gatsbyImageData(width: 800, placeholder: BLURRED, formats: [AUTO, WEBP])
      }
    }
  }
`;

// 渲染
const Hero = ({ data }) => {
  const image = getImage(data.file);
  return <GatsbyImage image={image} alt="Hero" />;
};

特性:自动生成多尺寸、WebP 格式、模糊占位图、懒加载。

五、部署

Gatsby 与 Gatsby Cloud(现为 Netlify 收购)、NetlifyVercel 深度集成:

# 构建产物在 public/
gatsby build

# Netlify:直接关联 Git 仓库,自动构建
# Vercel:框架预设选 Gatsby

六、与 Next.js / Astro 的对比

特性 Gatsby Next.js Astro
渲染方式 SSG SSG + SSR + ISR SSG + SSR
数据层 GraphQL 自选 自选
学习曲线 中等(需学 GraphQL) 中等
生态 丰富(3000+ 插件) 极其丰富 快速增长

七、思考题

  1. GraphQL 数据层适合什么场景?什么时候反而增加复杂度?
  2. 如果博客有 10000 篇文章,gatsby build 是否会变慢?如何优化?
  3. Gatsby 的 createPages 和 Remix 的文件系统路由哪种更灵活?

信息

路径
/tech-stacks/gatsby/tutorial/入门教程 - 从数据到静态站点.md
更新时间
2026/5/31