Reputation: 659
I need to import a npm package but failed when I use "import" statement like this
import { cuteLuna } from 'lunacomponent';
and I got an error : cannot use import statement outside a module
after I change it to dynamic import, it works.
const cuteLuna = dynamic(() => import('lunacomponent').then((a) => a.cuteLuna), {ssr: false});
My question is, why should I use dynamic import instead of usual import?
thanks!!
Upvotes: 7
Views: 9126
Reputation: 35573
Since Next.js is a framework that runs on server & client side it needs to consume the proper module styles for each.
Server side runs on Node, therefore your lib must expose a commonjs.
From your error I can guess that your lunacomponent
lib is not exporting cjs files, therefore it fails on the server, when you use dynamic
with ssr:false
you tell Next.js to skip server-side run, therefore you don't have the same error.
I wasn't able to find this lunacomponent
lib on the public npm registry, therefore I can't check my assumption.
Upvotes: 4