当我尝试使用wowjs构建我的gatsby项目时,它告诉我: “ WebpackError:ReferenceError:未定义窗口”或 '“ window”在服务器端渲染期间不可用。'
我在此网站上尝试了很多类似的操作:https://imedadel.me/fix-window-not-defined-gatsby,但没有任何效果。如果有人遇到相同的错误,很高兴知道如何消除它。
谢谢大家。
答案 0 :(得分:0)
在处理Gatsby和某些第三方模块或在组件中执行某些计算时,这是一个非常常见的问题。
gatsby develop
发生在浏览器端(总结),其中有一个window
对象。另一方面,gatsby build
发生在服务器端(您的计算机或部署系统)上,出于明显的原因,这里是there's no window
or other global objects。
如果您在组件/页面中使用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>;
};
如果问题来自代码的外部模块(第三方依赖项),则有两种选择:
通过添加新的webpack配置为该模块添加gatsby-node.js
加载程序,以替换null
中有问题的模块:
exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
if (stage === "build-html") {
actions.setWebpackConfig({
module: {
rules: [
{
test: /bad-module/,
use: loaders.null(),
},
],
},
})
}
}
请记住,该规则是一个与您的node_modules
中的文件夹名称匹配的正则表达式,您需要将/bad-module/
更改为已断开依赖项的文件夹名称(这就是为什么需要在斜杠(/
)之间添加它。在您的情况下,您似乎需要将/bad-module/
更改为/wowjs/
,但要确认路径。
使用loadable库:完成编译/构建后,而不是在SSR中,这将在浏览器端加载使用window
的动态模块( S erver- S ide( R 渲染)。