我在运行
gatsby build
时遇到了一个问题,这似乎很常见。
failed Building static HTML for pages - 5.310s
ERROR #95312
"window" is not available during server side rendering.
See our docs page for more info on this error: https://gatsby.dev/debug-html
ReferenceError: window is not defined
所以,根据互联网上的多篇文章,我首先尝试了检查我是否在浏览器环境中的方法。
const isBrowser = typeof window !== 'undefined';
构建仍然中断,所以这让我相信错误来自我在项目中的第 3 方依赖项。
所以我按照其他解决方案在
gatsby-config.ts
上添加一些配置以“绕过”一些构建步骤。
exports.onCreateWebpackConfig = ({ actions, loaders, stage }: any) => {
if (stage === 'build-html' || stage === 'develop-html' || stage === 'develop') {
actions.setWebpackConfig({
module: {
rules: [
{
test: /filler-module/,
use: loaders.null(),
},
],
},
});
}
};
也没有用。
所以,我的想法是在运行
gatsby build
时以某种方式绕过此检查。
有没有办法做到这一点?或者你看到这个错误的任何其他可能的解决方案吗?
谢谢。
首先澄清一下,当你说你尝试了 isBrowser 检查时,你实际上用
if(isBrowser) {window.example}
包装了对 window 的任何调用?检查你只提到在你的代码中放置那个特定的 const 定义 - 它需要在每个使用 window 的组件中定义,你仍然需要使用 if 语句检查 isBrowser 常量来实际包装对 window 的每个引用。
也就是说,如果您没有对窗口进行有问题的调用,听起来您可能正在使用不是为服务器端渲染编写的 React 依赖项。您可以尝试的一种 hacky 解决方案是使用库 “可加载组件” 在客户端引导期间加载整个组件而不是服务器渲染。您可以编写一个包装器组件,然后使用可加载组件调用您的实际组件:
import loadable from '@loadable/component';
import React from 'react';
export default function LoadableWrapperMyComponent() {
//Choose either Option A or B:
//Option A: MyComponent is a JSX file representing the component you need to wrap, specify a relative path to the file
const LoadableWrapperMyComponent = loadable(() => import('./MyComponent'), {
fallback: <div>Loading...</div>,
});
//Option B: Same as A, but for a component from an npm package
const LoadableWrapperMyComponent = loadable(() => import('some-npm-package/MyNPMComponent'), {
fallback: <div>Loading...</div>,
});
}
然后您可以简单地将这个可加载包装器导入并放置在您通常调用该组件的 JSX 代码中。