【问题标题】:Import npm when document is ready (ReactJS/Next.js)文档准备好时导入 npm (ReactJS/Next.js)
【发布时间】:2021-06-02 03:46:33
【问题描述】:

我正在尝试使用这个名为 float-sidebar.js 的小型 js 库,我已经通过 npm 安装了该模块,但我注意到在反应中它会抛出错误 "window" not defined,因为里面使用了 "window"模块内的代码 float-sidebar.min.js 不检查窗口是否已加载或准备好。

由于我使用的是 Next.js,因此我尝试像这样动态加载模块:

import dynamic from 'next/dynamic'
const FloatSidebar = dynamic(
  () => import('float-sidebar'),
  { ssr: false }
)

这样做不会再抛出“window”未定义错误,但它会说FloatSidebar 在我的代码中稍后不是函数:

const handleScroll = () => {

    const sidebar = document.querySelector('.sidebar');
    const relative = document.querySelector('.content');

    const floatSidebar = FloatSidebar({
      sidebar: sidebar,
      relative: relative,
      topSpacing: 40,
      bottomSpacing: 40
    });

    floatSidebar.forceUpdate();
  }

【问题讨论】:

标签: node.js reactjs npm next.js


【解决方案1】:

您可以在handleScroll 回调中简单地在float-sidebar 上使用常规的ES2020 dynamic import

const handleScroll = () => {
    const sidebar = document.querySelector('.sidebar');
    const relative = document.querySelector('.content');
    
    const FloatSidebar = (await import('float-sidebar')).default;
    const floatSidebar = FloatSidebar({
      sidebar: sidebar,
      relative: relative,
      topSpacing: 40,
      bottomSpacing: 40
    });
    floatSidebar.forceUpdate();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-13
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 2011-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多