简体   繁体   English

动态导入 - NextJS

[英]Dynamic Imports - NextJS

I have a simple function which loads a script:我有一个加载脚本的简单函数:

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;

Before I migrated to NextJS, I was importing the script with: import creditCardScript from "./creditCardScript" .在迁移到 NextJS 之前,我使用以下命令import creditCardScript from "./creditCardScript"脚本: import creditCardScript from "./creditCardScript"

Sine NextJS renders components server side in Node, care needs to be taken to ensure that any code with a reference to window (which is browser specific), doesn't get called until componentDidMount . Sine NextJS 在 Node 中呈现组件服务器端,需要注意确保任何引用window (特定于浏览器)的代码在componentDidMount之前不会被调用。

NextJS solves this issue by providing dynamic imports (a wrapper around react-loadable ) which: NextJS 通过提供动态导入(围绕react-loadable的包装器)解决了这个问题:

  • only load the component when needed,仅在需要时加载组件,
  • provides an option to only load the component on client side ( ssr: false ).提供仅在客户端加载组件的选项( ssr: false )。

I went ahead and implemented dynamic imports:我继续实施动态导入:

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

In componentDidMount :componentDidMount

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

But I'm getting this: Uncaught TypeError: Cannot call a class as a function但我得到了这个: Uncaught TypeError: Cannot call a class as a function

I've tried to convert the function to a class and use the constructor to pass in args , but my code now fails silently.我试图将函数转换为类并使用构造函数传入args ,但我的代码现在无声无息地失败了。

As Neal mentioned in the comments, all I need to do is something like this in componentDidMount :正如尼尔在评论中提到的,我需要做的就是在componentDidMount做这样的事情:

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

Link to the official tutorial 链接到官方教程

Export default only work with import from statement, you can try导出默认仅适用于import from语句,您可以尝试

export creditCardScript;

And on import, u can use like this在导入时,你可以这样使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM