655 字
3 分钟
Gatsby迁移指南:v3 To v4
NOTE
NOTE
升级 Gatsby 及其相关插件
yarn add -W \gatsby@^4.25.7 \gatsby-plugin-image@^2.25.0 \gatsby-plugin-sharp@^4.25.1 \gatsby-plugin-sitemap@^5.25.0 \gatsby-plugin-page-creator@^4.25.0 \gatsby-plugin-styled-components@^5.25.0 \gatsby-source-filesystem@^4.25.0 \gatsby-source-contentful@^7.23.1 \gatsby-transformer-sharp@^4.25.0问题处置
编译转换
Gatsby v4 版本可以启用新的 JSX 转换功能,即引入 React 不再是必须的:
import React from "react";但该转换配置默认为禁用模式,当一个组件未导入 React 时会报以下错误(看似毫不相干):

补充配置即可:
/** @type {import("gatsby").GatsbyConfig} */module.exports = { jsxRuntime: "automatic",};Optional 1 - 若使用了ESLint做代码校验,需添加插件eslint-plugin-react的扩展规则react/jsx-runtime,禁用检查:
extends: # ... - plugin:react/jsx-runtime # ...Optional 2 - 若使用了@svgr/cli转换 SVG 图标,需添加命令行参数--jsx-runtime=automatic启用新的转换规则(相应的@svgr/cli需要更新到 v6 版本以上),禁止生成 React 导入:
{ "svg": "npx @svgr/cli svg-dir --out-dir=xxx --ext=jsx --filename-case=kebab" "svg": "npx @svgr/cli svg-dir --out-dir=xxx --ext=jsx --filename-case=kebab --jsx-runtime=automatic"}依赖弃用
移除gatsby-plugin-compile-es6-packages依赖与配置,在上一个版本的升级中引入了该依赖处理图片插件不能正常工作的问题,现已不再需要。
迁移 gatsby-plugin-react-helmet
由于 react-helmet 已有 3 年未维护更新,同时 Gatsby v4 版本中支持(内置)了类似的解决方案。
Step 1 - 依赖变更
{ "name": "root", "version": "0.1.0", "dependencies": { "react-helmet": "^5.2.1", "gatsby-plugin-react-helmet": "^4.15.0" } // ...}Step 2 - 配置变更
/** @type {import("gatsby").GatsbyConfig} */module.exports = { plugins: [ 'gatsby-plugin-react-helmet', // ... ],}Step 3 - 使用变更
:::danger 注意 必须在会被创建为 Page 的组件中导出一个具名的 Head 组件(详见)。
以下行为会创建一个页面:
- 使用
createPages钩子创建 - 通过
gatsby-plugin-page-creator插件创建
:::
import Helmet from 'react-helmet' import { Fragment } from 'react'
export const SEO = ({ url, title, keywords, canonical, description }) => ( <Helmet title={title}> <Fragment> <title>{title}</title> <meta name="keywords" content={keywords} /> <meta name="canonical" content={canonical} /> <meta name="description" content={description} /> <meta property="og:url" content={url} /> <meta property="og:image:width" content="400" /> <meta property="og:image:height" content="300" /> </Fragment> </Helmet>)export default function PageComp({ data, pageContext }) { return ( <Xxx> <SEO {...props} /> </Xxx> )}
export function Head({ data, pageContext }) { return <SEO {...props} /> }迁移 gatsby-plugin-remove-trailing-slashes
该插件所提供的功能已在 Gatsby v4 版本中内置支持。
Step 1 - 依赖变更
{ "name": "root", "version": "0.1.0", "dependencies": { "gatsby-plugin-remove-trailing-slashes": "^2.2.1" } // ...}Step 2 - 配置变更
/** @type {import("gatsby").GatsbyConfig} */module.exports = { trailingSlash: 'never', plugins: [ 'gatsby-plugin-remove-trailing-slashes', // ... ],}若构建完成后出现类似以下错误或警告,请删除public文件夹后重新构建,因为更改了创建文件的行为,同时又有上一次的构建残留,出现了同名的文件与文件夹,被 Gatsby 检测到了冲突:


Gatsby迁移指南:v3 To v4
https://www.hzhi.top/posts/gatsby-v3-to-v4/