部署 Gatsby 站点
GraphQL 驱动的静态站点生成器,插件生态丰富,预构建 HTML/JSON 部署到任何 CDN。
平台进阶
为什么
Gatsby 构建时 GraphQL 数据层和图片优化生成极速静态站点,自动懒加载和预取。插件生态无缝连接 CMS(Contentful、WordPress、Sanity)。
平台即服务采用率 2024 年增长 24%,团队从虚拟机管理转向 git push 部署。the cloud infrastructure market reached $330B in 2024, growing 22% year-over-year (Synergy Research),PaaS 层捕获了大多数新工作负载。
何时使用
内容驱动且数据来自 CMS、构建时取数据可接受的站点用 Gatsby。高度动态内容避免 — 构建时间随数据增长。
如何做
1. 构建 — npm run build 生成 public/ 含 HTML、JSON、JS、CSS
2. 部署 — 上传 public/ 到任何静态主机(Gatsby Cloud、Vercel、Netlify、S3)
3. Gatsby Cloud — 优化构建含增量构建和云函数
4. 重定向 — gatsby-node.js createRedirect,或 netlify.toml/_redirects
5. 头 — gatsby-node.js 设缓存、安全头
6. 增量构建 — Gatsby Cloud 在部署间缓存构建加速
7. 预览 — gatsby-plugin-preview 用于 CMS 草稿预览
示例
// gatsby-config.js — 插件 + CMS 数据源
module.exports = {
plugins: [
"gatsby-plugin-image",
"gatsby-plugin-sharp",
{
resolve: "gatsby-source-contentful",
options: {
spaceId: process.env.CONTENTFUL_SPACE_ID,
accessToken: process.env.CONTENTFUL_ACCESS_TOKEN,
},
},
],
};
// gatsby-node.js — 重定向 + 头
exports.createPages = ({ actions }) => {
actions.createRedirect({ fromPath: "/old", toPath: "/new", isPermanent: true });
};
// netlify.toml — 部署配置
[build]
command = "npm run build"
publish = "public"
[[redirects]]
from = "/old"
to = "/new"
status = 301
常见问题
- ⚠构建耗时 20+ 分钟 — CMS 数据集大,用增量构建或分页
- ⚠图片未优化 — 忘记 gatsby-plugin-image 和 gatsby-plugin-sharp
- ⚠构建内存不足 — 增加 Node 堆:NODE_OPTIONS=--max-old-space-size=4096
最佳实践
- ✓用 Gatsby Cloud 增量构建 — 仅一页变更时避免全量重建
- ✓GraphQL 仅查所需字段 — 过度获取减慢构建并增大包
- ✓设置健康检查和优雅关闭 — 处理 SIGTERM 以在退出前排空进行中的请求