WebpackError:ReferenceError:Gatsby 上未定义窗口

Cef*_*ira 6 javascript reactjs webpack gatsby

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

我正在使用 Gasby 开发静态页面,但遇到此错误:

WebpackError: ReferenceError: window is not defined
Run Code Online (Sandbox Code Playgroud)

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

//index.js
import React from 'react'

const IndexPage = () => (
  <div>
  </div>
)
export default IndexPage
Run Code Online (Sandbox Code Playgroud)

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

Ps:我已经尝试在 componentDidMount 上导入 bootstrap 模块,我还尝试设置 gatsby-node.js 并且我还尝试使用可加载组件导入 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`,
Run Code Online (Sandbox Code Playgroud)

],

Fer*_*reu 8

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

在你的gatsby-node.js

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

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

您可以在 Gatsby 的文档中查看有关调试 HTML 构建的更多信息。