【发布时间】:2018-08-31 00:12:51
【问题描述】:
我无法弄清楚我在这里做错了什么/如何解决它。我正在使用 gatsby.js 和 bulma 构建一个站点。这是我第一次使用这两种方法,当我尝试构建它时遇到了一个问题:
WebpackError: document is not defined
我唯一使用 document 的地方是 bulma 文档中提供的 navbar-burger 切换代码。在开发中一切正常,但在构建生产时会中断。这是我的代码:
import React from 'react'
import Link from 'gatsby-link'
import Logo from '../img/logo.png'
const Navbar = ({ siteTitle }) => (
<div>
<nav className="navbar is-primary is-fixed-top">
<div className="container is-fluid">
<div className="navbar-brand">
<a className="navbar-item" href="../">
<img src={Logo} alt="Logo"/>
</a>
<a role="button" className="navbar-burger has-text-white" data-target="navMenu" aria-label="menu" aria-expanded="false">
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
</a>
</div>
<div className="navbar-menu" id="navMenu">
<div className="navbar-start has-text-white">
<a className="navbar-item">
Overview
</a>
<a className="navbar-item">
Overview
</a>
<a className="navbar-item">
Overview
</a>
<a className="navbar-item">
Overview
</a>
</div>
<div className="navbar-end has-text-white">
<a className="has-text-white navbar-item">
Overview
</a>
<div className="navbar-item">
<a className="button is-success is-fullwidth">
Request Demo
</a>
</div>
</div>
</div>
</div>
</nav>
</div>
);
document.addEventListener('DOMContentLoaded', () => {
// Get all "navbar-burger" elements
const $navbarBurgers = Array.prototype.slice.call(document.querySelectorAll('.navbar-burger'), 0);
// Check if there are any navbar burgers
if ($navbarBurgers.length > 0) {
// Add a click event on each of them
$navbarBurgers.forEach(el => {
el.addEventListener('click', () => {
// Get the target from the "data-target" attribute
const target = el.dataset.target;
const $target = document.getElementById(target);
// Toggle the "is-active" class on both the "navbar-burger" and the "navbar-menu"
el.classList.toggle('is-active');
$target.classList.toggle('is-active');
});
});
}
});
export default Navbar
非常感谢任何有关如何解决此问题的想法。 谢谢
【问题讨论】:
-
我不记得到底修复了什么。我想我最终删除了 node_modules 文件夹,确保 gatsby-cli 已更新,然后运行 npm install。
标签: javascript reactjs gatsby bulma