Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using `dynamic import` to fetch script from another host?

I run my next.js app on localhost:3001. I want to fetch script from another host (localhost:3000). I could do it like this. As for me, much prettier would be using dynamic import. But I got an error: 'ModuleNotFoundError: Module not found: Error: Can't resolve 'http://localhost:3000/static/fileToFetch.js' in '/Users/{username}/Desktop/test-project/pages';

Example:

export const FetchedComponent = dynamic({
  loader: () =>
    import('http://localhost:3000/static/fileToFetch.js'),
  loading: () => 'Loading...',
  ssr: false,
});

Is it possible to do it?

like image 991
Oleksandr Blyzniuk Avatar asked Mar 04 '23 11:03

Oleksandr Blyzniuk


1 Answers

Dynamic import with webpack is works only for code splitting. you need to find out how to tell to webpack not to change the import() and then enable CORS in that domain.

An alternative way would be to write a function that will inject script tag to the body and return a promise, something like that:

function importExternal(url) {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.src = url;
    script.async = true;
    script.onload = () => resolve(window['external_global_component']);
    script.onerror = reject;

    document.body.appendChild(script);
  });
}

When the file that you are loading, putting on the global (external_global_component) the component that was loaded. And then, you will able to use it with NextJS dynamic.

export const FetchedComponent = dynamic({
  loader: () =>
    importExternal('http://localhost:3000/static/fileToFetch.js'),
  loading: () => 'Loading...',
  ssr: false, // <- must be false, because we are using DOM.
});
like image 156
felixmosh Avatar answered Mar 15 '23 08:03

felixmosh