7

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

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.