如何将 FastClick 添加到 Next.JS?

How to add FastClick to Next.JS?

当我尝试修改 pages/_document.js 以添加 FastClick 事件注册(见下文)时,它抱怨 ReferenceError: document is not defined。我想这是因为它是在服务器上执行的,而 document 没有在那里定义。有什么办法解决吗?

if ('addEventListener' in document) {
  document.addEventListener('DOMContentLoaded', function() {
    FastClick.attach(document.body)
  }, false)
}

您可以使用 process.browser 来确保您的代码仅在前端执行。

if (process.browser) {
  document.addEventListener('DOMContentLoaded', function() {
    FastClick.attach(document.body)
  }, false)
}

pages/_document.js 仅根据 next.js documentation.

在服务器上呈现

我建议在 pages/_app.js 中使用该代码,它将在所有组件之间共享。