如何绕过 Gatsby 构建期间未定义的 window?如果检查不起作用

How do I get around window not defined during Gatsby build? If check is not working

我的一个道具使用条件运算符来确定导航元素的颜色。但是该语句需要 window.location.pathname,这会在构建过程中导致此错误。

WebpackError: ReferenceError: window is not defined

我试图做的是从 wordpress 中拉入 slug,如果它与当前页面 slug 匹配,它将显示活动颜色。

这是我的代码片段,其中检查了样式化组件内的 window。确认条件在开发中正常工作。

const noBrowser = () => typeof window === "undefined"
color:  ${props=> noBrowser()?'#000':(props.to===window.location.pathname? '#05C079ff':'#F21C5Eff')};

但这似乎没有发现缺少浏览器 window,我仍然遇到同样的错误。

有人对如何解决这个问题有什么建议吗?这些页面是通过 graphql 从 wordpress slugs 生成的。链接生成为图标。

你试过这样的东西吗?

color:  ${props => noBrowser ? '#000' : (props.to===window.location.pathname? '#05C079ff':'#F21C5Eff')};

或者直接反转条件:

color:  ${props=> typeof window !== "undefined" ? (props.to===window.location.pathname? '#05C079ff':'#F21C5Eff') : '#000':};