【问题标题】:Dynamic Imports - NextJS动态导入 - NextJS
【发布时间】:2019-05-28 13:14:31
【问题描述】:

我有一个加载脚本的简单函数:

const creditCardScript = (
  onReadyCB,
  onErrorCB,
) => {
  let script = document.createElement("script");
  script.type = "text/javascript";
  script.src = process.CREDIT_CARD_SCRIPT;
  document.head.appendChild(script);

  script.onload = function() {
    ...
  };
};

export default creditCardScript;

在迁移到 NextJS 之前,我使用以下代码导入脚本:import creditCardScript from "./creditCardScript"

Sine NextJS 在 Node 中呈现组件服务器端,需要注意确保引用 window(特定于浏览器)的任何代码在 componentDidMount 之前不会被调用。

NextJS 通过providing dynamic importsreact-loadable 的包装)解决了这个问题:

  • 仅在需要时加载组件,
  • 提供仅在客户端加载组件的选项 (ssr: false)。

我继续执行动态导入:

const creditCardScript = dynamic(import("./creditCardScript"), { ssr: false });

componentDidMount:

componentDidMount = () => {
  creditCardScript(
    this.onReadyCB,
    this.onErrorCB
  );
};

但我得到了这个: Uncaught TypeError: Cannot call a class as a function

我尝试将函数转换为类并使用构造函数传入args,但我的代码现在静默失败。

【问题讨论】:

    标签: javascript node.js reactjs next.js react-loadable


    【解决方案1】:

    正如 cmets 中提到的 Neal,我需要做的就是在 componentDidMount 中进行类似这样的操作:

    const { default: creditCardScript } = await import("./creditCardScript"); 
    

    Link to the official tutorial

    【讨论】:

    • 我很困惑,为什么不直接使用常规函数?
    • 然后在客户端唯一的生命周期钩子中调用它。不要使用动态功能 - 仅适用于反应组件。
    【解决方案2】:

    导出默认只对import from语句有效,你可以试试

    export creditCardScript;
    

    在导入时,你可以这样使用

    const {creditCardScript} = dynamic(import("./creditCardScript"), { ssr: false });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 2020-11-06
      • 1970-01-01
      • 2021-06-19
      • 2021-12-23
      • 2020-12-19
      • 1970-01-01
      相关资源
      最近更新 更多