如何在本地插件中将 Gatsbys wrapPageElement 与 Typescript 一起使用?

How to use Gatsbys wrapPageElement with Typescript in a local plugin?

我正在尝试创建一个新的 Gatsby 插件。我开始将其开发为 a local plugin。在这个插件中,我想在 运行 时间内为服务器端渲染提供 wrapPageElement,因此我创建了以下配置文件:

盖茨比-ssr.js:

export { wrapPageElement } from "./src/wrapPageElement";

盖茨比-browser.js:

export { wrapPageElement } from "./src/wrapPageElement";

src/wrapPageElement.tsx:

import React from "react";
import { GatsbyBrowser, GatsbySSR } from "gatsby";

type WrapPageElement =
  | GatsbyBrowser["wrapPageElement"]
  | GatsbySSR["wrapPageElement"];

export const wrapPageElement: WrapPageElement = ({ element, props }: any) => {
  return <div {...props}>{element}</div>;
};

现在,当我 运行 我的 Gatsby 项目时,我得到以下 运行 时间错误:

One unhandled runtime error found in your files. See the list below to fix it:

Unknown Runtime Error

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of `PageRenderer`.
:

No codeFrame could be generated

当我不尝试在 wrapPageElement 中呈现 {element} 时,例如一个简单的字符串,wrapPageElement 会成功呈现。问题似乎与 element 有关。有人知道这里出了什么问题吗?

我使用的是 Gatsby 版本 3.14.0

根据 this GitHub thread,似乎尚未解决(尚未),其中显然 Gatsby 未正确导出类型。

作为一个 hacky 解决方法,您可以尝试:

type Fn = (...args: Parameters<WrapPageElement>) => ReturnType<WrapPageElement>

export const wrapPageElement: Fn = ({ element, props }: any) => {
  return <div {...props}>{element}</div>;
};

注:修改自GitHub的线程

中的源代码

问题是,我尝试呈现的页面没有默认导出。

而不是..

import React from "react";

export default function IndexPage() {
  return <div>
    Index
  </div>
}

..我定义了..

import React from "react";

export function IndexPage() {
  return <div>
    Index
  </div>
}

.. 错误原因。