391 字
2 分钟
Gatsby迁移指南:v4 To v5
NOTE

官方迁移指南

NOTE

书接上回 Gatsby 迁移指南: v2 To v3

书接上回 Gatsby 迁移指南: v3 To v4

提升 Node 版本上限#

- image: node:16.19.1-rsync
+ image: node:18.17.0-rsync
{
  "name": "root",
  "version": "0.1.0",
  "engines": {
-   "node": ">= 16"
+   "node": ">= 18"
  }
  // ...
}

升级 React v18#

yarn add -W react@^18.2.0 react-dom@^18.2.0

可选的类型安装:

yarn add -W -D @types/react@^18.2.18 @types/react-dom@^18.2.7

若使用了renderunmountComponentAtNode创建与销毁组件,可迁移createRoot API:

- import { render, unmountComponentAtNode } from 'react-dom'
+ import { createRoot } from 'react-dom/client'

const ele = document.getElementById('xxx')

- render(<XxxComp />, ele)
- unmountComponentAtNode(ele)

+ const root = createRoot(ele)
+ root.render(<XxxComp />)
+ root.unmount()

升级 Gatsby 及其相关插件#

yarn add -W \
gatsby@^5.11.0 \
gatsby-plugin-image@^3.11.0 \
gatsby-plugin-sharp@^5.11.0 \
gatsby-plugin-sitemap@^6.11.0 \
gatsby-plugin-page-creator@^5.11.0 \
gatsby-plugin-styled-components@^6.11.0 \
gatsby-source-filesystem@^5.11.0 \
gatsby-source-contentful@^8.11.0 \
gatsby-transformer-sharp@^5.11.0

问题处置#

迁移 GraphQL 字段语法#

排序(sort)与聚合(distinct)字段的参数已由枚举传递变更为嵌套对象输入。

在 Gatsby v5 版本中会对其进行自动转换并输出警告信息,如图所示:

graphql-nested

根据警告信息对相应的代码进行调整即可:

graphql`
  query {
-   data: allContentfulNews(sort: { fields: createdAt, order: DESC }) {
+   data: allContentfulNews(sort: { createdAt: DESC }) {
      # ...
    }
  }
`
graphql`
  query {
-   data: allContentfulNews(sort: { fields: [rank, date] }) {
+   data: allContentfulNews(sort: { rank: ASC, date: ASC }) {
      # ...
    }
  }
`

迁移 StaticQuery 组件调用#

组件<StaticQuery />在 Gatsby v5 版本中已标记为弃用,将于 v6 版本正式移除,可提前将其迁移至useStaticQuery,由于只是书面形式上的变更,参考迁移指南即可。

迁移组件风格: 由于在 class component 中不能使用 Hooks,因此也需要将 class component 改写为 function component。

Gatsby迁移指南:v4 To v5
https://www.hzhi.top/posts/gatsby-v4-to-v5/
作者
Jim的独立博客
发布于
2023-09-15
许可协议
CC BY-NC-SA 4.0