【问题标题】:WebpackError: ReferenceError: window is not defined on GatsbyWebpackError:ReferenceError:Gatsby 上未定义窗口
【发布时间】:2020-12-02 11:50:59
【问题描述】:

我已经在互联网上进行了大量搜索,但无法解决这个问题。

我正在使用 Gasby 开发一个静态页面,我遇到了这个错误:

WebpackError: ReferenceError: window is not defined

我的线索是,这与我正在使用的 bootsrap/Modal 模块有关。但是我已经清理了我所有的 index.js 并且当我尝试构建它时仍然收到错误。

//index.js
import React from 'react'

const IndexPage = () => (
  <div>
  </div>
)
export default IndexPage

有人知道我该如何解决吗?谢谢!

Ps:我已经尝试在 componentDidMount 上导入 bootstrap 模块,我也尝试设置 gatsby-node.js 并且我还尝试使用 loadable-components 导入 bootstrap 模块。

Edit1:来自 gatsby-config.js 的插件部分

  plugins: [
`gatsby-plugin-react-helmet`,
{
  resolve: `gatsby-source-filesystem`,
  options: {
    name: `images`,
    path: `${__dirname}/src/images`,
  },
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
  resolve: `gatsby-plugin-manifest`,
  options: {
    name: `ayo`,
    short_name: `ayo`,
    start_url: `/`,
    background_color: `#fff`,
    theme_color: `#20336C`,
    display: `minimal-ui`,
    icon: `src/images/icon.png`, // This path is relative to the root of the site.
  },

},
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.dev/offline
// `gatsby-plugin-offline`,

],

【问题讨论】:

  • 如果您的项目甚至没有实现引导模式,是什么让您怀疑它?您可以发布 gatsby.config 的插件部分吗?
  • 我用 if 语句编辑了 node_modules 文件夹中的 modal.js 文件,项目就建好了。但我不认为这是一个解决方案,除非我将 node_modules 推送到 github。但这不是一个好的做法。 _setResizeEvent() { if(typeof window !== 'undefined'){ if (this._isShown) { $(window).on(EVENT_RESIZE, (event) => this.handleUpdate(event)) } else { $(window ).off(EVENT_RESIZE) } } }
  • 您可以通过gatsby-browser.js导入您想要的代码。你能发布你的包 JSON 吗?
  • Bootstrap 插件依赖于 Jquery 以及可能需要在 gatsby-browser.js 中导入的 bootstrap 之外的其他代码。如果您只想要一个模态,那么有一种更简单的方法来获得它。

标签: javascript reactjs webpack gatsby


【解决方案1】:

当使用第三方依赖项(例如您的 Bootstrap 模式)时,您访问 window 对象的能力会消失。在这种情况下,你必须为这个模块的 webpack 配置添加一个 null 加载器。

在你的gatsby-node.js:

exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
  if (stage === "build-html") {
    actions.setWebpackConfig({
      module: {
        rules: [
          {
            test: /bad-module/,
            use: loaders.null(),
          },
        ],
      },
    })
  }
}

在上面的代码中,您必须将 /bad-module/ 替换为您想要避免转换的 node_modules 中的依赖项文件夹。基本上,您在服务器渲染期间将有问题的模块替换为一个虚拟模块,因为它是一个正则表达式,您必须将您的模块名称与文件夹匹配。

您可以在Gatsby's documentation about debugging HTML builds查看更多信息。

【讨论】:

    猜你喜欢
    • 2021-06-16
    • 2014-09-02
    • 2017-10-01
    • 2021-09-21
    • 1970-01-01
    • 2021-10-06
    • 2019-06-03
    • 2021-01-15
    • 2019-10-12
    相关资源
    最近更新 更多