Skip to content
Advertisement

Dynamic Import Node Module With Next.js

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';

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement