我正在使用盖茨比建立网站。我添加了React Booking Calendar来显示一些日历数据。
运行“ gatsby开发”效果很好,但是运行“ gatsby build”会产生以下错误:
f=h(function(){return/msie [6-9]\b/.test(self.navigator.userAgent.toLowerCase())})
在错误发生之前,它会打印react-booking-calendar index.js的整个压缩版本。在该Blob中搜索,我可以看到“自我”出现了一次:
{{1}}
对于这个问题,我将不胜感激。谢谢。
盖茨比版本:盖茨比CLI版本:2.12.8 节点版本:v13.13.0 反应预订日历:^ 1.0.3
答案 0 :(得分:1)
正如@Hades所指出的,由于资产编译和JavaScript捆绑,Gatsby的行为在develop
和build
之间可能有所不同。您可以在Gatsby's documentation about debugging中查看更多信息。
要绕过错误并进行编译,您可以选择以下几种方法:
等待直到在使用window
的组件/函数中定义了f=h(function(){return/msie [6-9]\b/.test(self.navigator.userAgent.toLowerCase())})
。使用类似这样的东西:
if (typeof window !== 'undefined') {
f=h(function(){return/msie [6-9]\b/.test(self.navigator.userAgent.toLowerCase())})
}
更改Webpack的配置,以将null
加载程序用于您的第三方库,并在gatsby-node.js
中使用:
exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
if (stage === "build-html") {
actions.setWebpackConfig({
module: {
rules: [
{
test: /react-booking-calendar/,
use: loaders.null(),
},
],
},
})
}
}
将代码放入componentDidMount
生命周期或useEffect
挂钩中,以确保执行代码时已经定义了window
。
答案 1 :(得分:0)
在develop
中运行时,大多数情况下是在浏览器中运行React SPA。
在运行build
时,您主要在节点上运行,该节点对浏览器一无所知-您正尝试访问浏览器的navigator
。
由于节点没有某些事物的概念,例如DOM,document
,window
等,因此您需要使用反应挂钩和状态管理来访问它们,即使如此,这也是一个好习惯检查它们是否首先存在。