入门篇 - Gatsby数据层与页面生成

知识库
知识库文档
/tech-stacks/gatsby/tutorial/入门篇 - Gatsby数据层与页面生成.md

文档

Gatsby 数据层与页面生成入门

背景

Gatsby 曾是 JAMStack 的旗帜。虽然近年来 Astro 和 Next.js 抢了风头,但 Gatsby 的 GraphQL 数据层 + 插件生态仍然是内容驱动网站的优秀方案。毕设中如果你需要从多个数据源(CMS、Markdown、API)聚合内容并生成静态网站,Gatsby 是最成熟的方案。


核心概念

GraphQL 数据层

Gatsby 最独特的特性:所有数据都通过 GraphQL 统一访问。

数据源(Markdown、CMS、API、JSON、数据库)
        ↓
   Gatsby Source Plugins
        ↓
   GraphQL Data Layer(统一数据层)
        ↓
   React 页面组件(通过 graphql 查询)

插件系统

// gatsby-config.js
module.exports = {
  plugins: [
    'gatsby-plugin-image',           // 图片优化
    {
      resolve: 'gatsby-source-filesystem',
      options: { name: 'posts', path: './content/posts/' }
    },
    'gatsby-transformer-remark',     // Markdown → HTML
  ]
};

分步操作

第一步:创建项目

npm install -g gatsby-cli
gatsby new my-site
cd my-site
gatsby develop

第二步:探索数据层

访问 http://localhost:8000/___graphql,这是 Gatsby 的 GraphQL 浏览器:

query {
  site {
    siteMetadata {
      title
    }
  }
  allFile {
    nodes {
      name
      extension
    }
  }
}

第三步:页面查询

// src/pages/index.js
import { graphql } from 'gatsby';

export default function Home({ data }) {
  return <h1>{data.site.siteMetadata.title}</h1>;
}

export const query = graphql`
  query HomeQuery {
    site {
      siteMetadata { title }
    }
  }
`;

第四步:程序化创建页面

// gatsby-node.js
exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions;
  const result = await graphql(`
    query { allMarkdownRemark { nodes { frontmatter { slug } } } }
  `);

  result.data.allMarkdownRemark.nodes.forEach(node => {
    createPage({
      path: `/blog/${node.frontmatter.slug}`,
      component: require.resolve('./src/templates/blog-post.js'),
      context: { slug: node.frontmatter.slug },
    });
  });
};

毕设推荐场景

个人技术博客

Markdown 写作 + Gatsby 生成 = 部署到 GitHub Pages。

作品集网站

JSON/YAML 管理项目数据,GraphQL 查询渲染。

多数据源聚合

同时展示 GitHub API + Markdown + CMS 内容。


思考题

  1. GraphQL 数据层相比直接 fetch API 有什么优势?
  2. gatsby-node.js 中的 createPages 在构建时还是运行时执行?
  3. Gatsby 的插件系统设计对开发效率有什么影响?

小结

Gatsby 的 GraphQL 数据层是它区别于其他 SSG 的核心特色。虽然学习曲线略高,但对多数据源聚合场景,它是最优雅的方案。

信息

路径
/tech-stacks/gatsby/tutorial/入门篇 - Gatsby数据层与页面生成.md
更新时间
2026/5/30