wow.js 和 Gatsby 的 WebpackError

WebpackError with wow.js and Gatsby

当我尝试使用 wowjs 构建我的 gatsby 项目时,它告诉我: 'WebpackError: ReferenceError: window is not defined' 或 “”window”在服务器端呈现期间不可用。'

我在这个网站上尝试了很多方法:https://imedadel.me/fix-window-not-defined-gatsby 但没有任何效果。如果有人遇到同样的错误,很高兴知道如何摆脱它。

谢谢大家

在处理 Gatsby 和某些 third-party 模块或在您的组件中执行一些计算时,这是一个非常常见的问题。

gatsby develop 出现在 browser-side(总结)中,那里有一个 window 对象。另一方面,gatsby build 出现在 server-side(您的机器或您的部署系统)上,出于显而易见的原因,there's no window or other global objects.

如果您在 component/pages 中使用 window 对象,您只需创建一个简单的条件来检查 window 对象是否可用:

export const YourComponent = (props) => {

  if (typeof window !== 'undefined'){
     console.log('window width is', window.innerWidth)
  };

  return <div>I've checked the type of the window to make some calculations, preventing the code-breaking in the build time in SSR</div>;
};

如果问题来自代码的外部模块(third-party 依赖项),您有两个选择:

  • 通过添加新的 webpack 配置来为该模块添加 null 加载程序,从而替换 gatsby-node.js 中有问题的模块:

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

    请记住,规则是匹配文件夹名称 inside 您的 node_modules 的正则表达式,您需要将 /bad-module/ 更改为您的文件夹名称破坏的依赖性(这就是为什么你需要在斜杠之间添加它(/))。在您的情况下,您似乎需要将 /bad-module/ 更改为 /wowjs/ 但确认路径。

  • 使用loadable库:这将在browser-side中加载使用window的动态模块,一旦compilation/build完成,不在 SSR 中 (Server-Side Rendering).