WebPackError:ReferenceError:未在Gatsby上定义窗口 [英] WebpackError: ReferenceError: window is not defined on Gatsby

查看:21
本文介绍了WebPackError:ReferenceError:未在Gatsby上定义窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Internet上搜索了很久,但无法解决这个问题。

我正在使用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,还尝试过导入带有可加载组件的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`,

],

推荐答案

使用第三方依赖项(如引导模式)时,您访问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(),
          },
        ],
      },
    })
  }
}
在上面的代码中,您必须将node_modules中要避免传输的依赖项文件夹替换为/bad-module/。基本上,您是在服务器呈现过程中用伪模块替换有问题的模块,因为它是正则表达式,所以您必须将模块名称与文件夹匹配。

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

这篇关于WebPackError:ReferenceError:未在Gatsby上定义窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆