代码之家  ›  专栏  ›  技术社区  ›  Robin

如何在本地插件中使用Gatsbys wrappePageElement和Typescript?

  •  0
  • Robin  · 技术社区  · 3 年前

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

    gatsby-ssr.js :

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

    gatsby-browser.js :

    从“./src/wrappePageElement”导出{wrappePageElement};
    

    src/wrappePageElement.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
    

    当我不尝试渲染时 {element} wrappePageElement ,例如一个简单的字符串 wrappePageElement 已成功渲染。这个问题似乎与 element .有人知道这里出了什么问题吗?

    我在盖茨比版本 3.14.0 .

    0 回复  |  直到 3 年前
        1
  •  1
  •   Ferran Buireu    3 年前

    根据 this GitHub thread ,而盖茨比显然没有正确出口类型。

    作为一种巧妙的变通方法,您可以尝试:

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

    注意:从GitHub线程中的源代码修改

        2
  •  -1
  •   Robin    3 年前

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

    而不是

    import React from "react";
    
    export default function IndexPage() {
      return <div>
        Index
      </div>
    }
    

    ..我定义了。。

    import React from "react";
    
    export function IndexPage() {
      return <div>
        Index
      </div>
    }
    

    ..是什么导致了错误。