@typeform/embed 破坏了 Gatsby Netlify 构建

@typeform/embed breaks Gatsby Netlify build

我已经按照 typeform 嵌入说明进行操作,甚至按照他们的建议切换到 yarn 包管理器,但我在构建过程中一直遇到错误。

5:27:38 PM: failed Building static HTML for pages - 4.592s

5:27:38 PM: error Building static HTML failed


5:27:38 PM: > 1 | !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","react-dom"],t):"object"==typeof exports? 

这个错误不断出现。

但是,一旦我停止导入 typeform,我就没有任何问题。 这条线是罪魁祸首。

import * as typeformEmbed from "@typeform/embed";

如果我摆脱它,只是 return 一个空 div 我没有任何问题。

这是整个组件

import React, { useRef, useEffect } from "react";
import * as typeformEmbed from "@typeform/embed";

const Form = () => {
    const typeformRef = useRef(null);

    useEffect(() => {
        typeformEmbed.makeWidget(
            typeformRef.current,
            "https://tu6s6xuakuw.typeform.com/to/wGd96IFk",
            {
                hideFooter: true,
                hideHeaders: true,
                opacity: 50,
            }
        );
    }, [typeformRef]);

    return (
        <div ref={typeformRef} style={{ height: "500px", width: "100%" }}></div>
    );
};

export default Form;

如能提供任何线索,我们将不胜感激。

在您的 gatsby-node.js 中添加以下代码段:

exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
    if (stage === 'build-html') {
        actions.setWebpackConfig({ 
            module: {
                rules: [
                  {
                    test: /@typeform/,
                    use: loaders.null(),
                  },
                ],
              }
        })
    }
}

在 Gatsby 中处理使用 window 的第三方模块时,您需要将 null 加载器添加到其自己的 webpack 配置中,以避免在 SSR 期间进行转译( S服务器-SideR渲染)。这是因为 gatsby develop 出现在浏览器中,而 gatsby build 出现在 Node 服务器中,显然没有 window or other global objects.

请记住,test 值是一个正则表达式,将匹配 node_modules 下的文件夹,因此,请确保 /@typeform/ 是正确的名称(您可能需要将其更改为 /@typeform/\embed/).