Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 1000
Seldon Stone Avatar asked Oct 23 '18 00:10

Seldon Stone


People also ask

How do I import a dynamic module in node js?

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

What is the use dynamic import in next JS?

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.

Is next JS dynamic?

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).

When should I use next dynamic import?

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.


1 Answers

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.

like image 94
iurii Avatar answered Oct 10 '22 09:10

iurii