Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot use import statement outside a module with Next.js

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!!

like image 417
Doraemon Avatar asked Aug 10 '26 16:08

Doraemon


1 Answers

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.

like image 114
felixmosh Avatar answered Aug 12 '26 10:08

felixmosh