I was getting an error of window undefined when using react-leaflet node module because it relies on window and of course SSR does not support window. I found next/dynamic, however, all the examples I found show how to import a component and not a node module. Is it possible to include a node module and if so how? As an example this is what I'm importing that is giving the window undefined error import { Map, TileLayer, Marker } from 'react-leaflet';
To load dynamically a module call import(path) as a function with an argument indicating the specifier (aka path) to a module. const module = await import(path) returns a promise that resolves to an object containing the components of the imported module. } = await import(path);
Next.js supports lazy loading external libraries with import() and React components with next/dynamic . Deferred loading helps improve the initial loading performance by decreasing the amount of JavaScript necessary to render the page.
Next. js supports ES2020 dynamic `import()` for JavaScript. With it, you can import JavaScript modules dynamically and work with them. They also work with server-side rendering (SSR).
Dynamic imports are fetched when the component is rendered for the first time. Already rendered imports do not trigger an additional re-fetch. Each dynamic import will create a newly incremented bundle file.
The issue is that next.js dynamic import fails on named exports
Looking at the source code of react-leaflet I can see that each named export can be accessed from a particular file e.g. import Map from 'react-leaflet/lib/Map'
Combine it with dynamic import without SSR
const Map = dynamic(() => import('react-leaflet/lib/Map'), {
ssr: false
});
This should do a trick for you.
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