title: Dynamic Imports - NextJS
body: <p>I have a simple function which loads a script:</p>
  
  <pre><code>const creditCardScript = (
    onReadyCB,
    onErrorCB,
  ) =&gt; {
    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;
  </code></pre>
  
  <p>Before I migrated to NextJS, I was importing the script with: <code>import creditCardScript from "./creditCardScript"</code>.</p>
  
  <p>Sine NextJS renders components server side in Node, care needs to be taken to ensure that any code with a reference to <code>window</code> (which is browser specific), doesn't get called until <code>componentDidMount</code>.</p>
  
  <p>NextJS solves this issue by <a href="https://nextjs.org/docs/#3-with-no-ssr" rel="nofollow noreferrer">providing dynamic imports</a> (a wrapper around <a href="https://github.com/jamiebuilds/react-loadable" rel="nofollow noreferrer">react-loadable</a>) which:</p>
  
  <ul>
  <li>only load the component when needed,  </li>
  <li>provides an option to    only load the component on client side
  (<code>ssr: false</code>).</li>
  </ul>
  
  <p>I went ahead and implemented dynamic imports:</p>
  
  <pre><code>const creditCardScript = dynamic(import("./creditCardScript"), { ssr: false });
  </code></pre>
  
  <p>In <code>componentDidMount</code>:</p>
  
  <pre><code>componentDidMount = () =&gt; {
    creditCardScript(
      this.onReadyCB,
      this.onErrorCB
    );
  };
  </code></pre>
  
  <p>But I'm getting this:
  <code>Uncaught TypeError: Cannot call a class as a function</code></p>
  
  <p>I've tried to convert the function to a class and use the constructor to pass in <code>args</code>, but my code now fails silently.</p>