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?
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.
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With