首页 > 解决方案 > Gatsby + React 预订日历:“WebpackError: ReferenceError: self is not defined” on 'gatsby build' 但 'gatsby develop' 工作正常

问题描述

我正在使用 Gatsby 建立一个网站。我添加了React Booking Calendar来显示一些日历数据。

运行 'gatsby develop' 工作正常,但运行 'gatsby build' 会产生以下错误:

WebpackError: ReferenceError: self is not defined

  - index.js:13
    node_modules/react-booking-calendar/lib/index.js:13:10310

  - index.js:13
    node_modules/react-booking-calendar/lib/index.js:13:10234

  - index.js:13 e.exports
    node_modules/react-booking-calendar/lib/index.js:13:10505

  - index.js:13 Object.<anonymous>
    node_modules/react-booking-calendar/lib/index.js:13:11026

  - index.js:1 t
    node_modules/react-booking-calendar/lib/index.js:1:328

  - index.js:12 Object.<anonymous>
    node_modules/react-booking-calendar/lib/index.js:12:5444

  - index.js:1 t
    node_modules/react-booking-calendar/lib/index.js:1:328

  - index.js:1 Object.<anonymous>
    node_modules/react-booking-calendar/lib/index.js:1:519

  - index.js:1 t
    node_modules/react-booking-calendar/lib/index.js:1:328

  - index.js:1
    node_modules/react-booking-calendar/lib/index.js:1:401

  - index.js:1
    node_modules/react-booking-calendar/lib/index.js:1:437

  - index.js:1
    node_modules/react-booking-calendar/lib/index.js:1:65

  - index.js:1 Object../node_modules/react-booking-calendar/lib/index.js
    node_modules/react-booking-calendar/lib/index.js:1:211

它在错误之前打印整个缩小版本的 react-booking-calendar index.js。在那个 blob 中搜索,我可以看到“self”出现一次:

f=h(function(){return/msie [6-9]\b/.test(self.navigator.userAgent.toLowerCase())})

我将不胜感激有关此问题的任何建议。谢谢。


Gatsby 版本:Gatsby CLI 版本:2.12.8 节点版本:v13.13.0 React 预订日历:^1.0.3

标签: reactjswebpackgatsby

解决方案


正如@Hades 指出的那样,Gatsby 的行为可能会因资产编译和 JavaScript 捆绑而develop有所不同。您可以在Gatsby 的有关调试的文档build中查看更多信息。

要绕过您的错误并进行编译,您有几个选项:

  • 等待直到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在执行代码时已经定义了它。


推荐阅读