Dynamic Imports - NextJS

10,184

Solution 1

As Neal mentioned in the comments, all I need to do is something like this in componentDidMount:

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

Link to the official tutorial

Solution 2

Export default only work with import from statement, you can try

export creditCardScript;

And on import, u can use like this

const {creditCardScript} = dynamic(import("./creditCardScript"), { ssr: false });
Share:
10,184
Avi Kaminetzky
Author by

Avi Kaminetzky

Updated on June 04, 2022

Comments

  • Avi Kaminetzky
    Avi Kaminetzky almost 2 years

    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".

    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.

    NextJS solves this issue by providing dynamic imports (a wrapper around react-loadable) which:

    • only load the component when needed,
    • provides an option to only load the component on client side (ssr: false).

    I went ahead and implemented dynamic imports:

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

    In componentDidMount:

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

    But I'm getting this: 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.

  • Naftali
    Naftali over 5 years
    I am confused, why not just use a regular function?
  • Naftali
    Naftali over 5 years
    And then call it during a client side only lifecycle hook. Dont use the dynamic function -- that is only for react components.