0

I've been trying to use Dynamic Importing in Nextjs in order to use the screenfull library but it hasn't worked.

import dynamic from "next/dynamic"
import screenfull from 'screenfull';
const Screenfull = dynamic(()=>{return import("screenfull")},{})
Diandre402
  • 64
  • 4
  • [`next/dynamic`](https://nextjs.org/docs/advanced-features/dynamic-import#basic-usage) is used to dynamically import _React_ components. To import regular JavaScript libraries you can simply use dynamic `import`. See [Why am I getting ReferenceError: self is not defined in Next.js when I try to import a client-side library?](https://stackoverflow.com/a/66100185/1870780) for an example. – juliomalves Nov 03 '21 at 23:47

3 Answers3

0

you can create file in @utils folder with below code:

import screenfull from 'screenfull';

export default screenfull

then in your component do something like so:

import dynamic from 'next/dynamic';
const screenful = dynamic(() => import('../@utils/screenfull'))

0

The first question that comes to mind is what's the error you're getting? There's no reason you shouldn't be able to import any library you've installed locally! Did you actually install that package by running npm install screenfull on your terminal?

Data Crusader
  • 425
  • 1
  • 4
  • 14
  • Yes! I did install screenfull locally. The errors I got were: "Module not found", "can't resolve" and "document is not defined" – Diandre402 Nov 03 '21 at 20:24
0

You're using dynamic imports incorrectly. The idea is that you can import part of a JS module inside of another piece of JS code, so you don't have to preload or load the entire library. An example might be doing a dynamic import after an async call.

Next has some other great examples of how to use this functionality in your application.

serraosays
  • 7,163
  • 3
  • 35
  • 60