Web/Library

[Konva] Next에서 Konva사용하기

레에몽 2022. 3. 9. 15:54

 Konva를 Next에서 사용하려니까 다음과 같은 이슈가 발생했습니다.

 

Error: Must use import to load ES Module: C:\Users\??\dev\atomic\node_modules\konva\lib\Core.js
require() of ES modules is not supported.
require() of C:\Users\??\dev\atomic\node_modules\konva\lib\Core.js from C:\Users\??\dev\atomic\node_modules\react-konva\lib\ReactKonvaCore.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename Core.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from C:\Users\??\dev\atomic\node_modules\konva\package.json.

 

여기서 권장하는 방법은 `./node_modules/react-konva/package.json`에 "type": "module"을 추가하는 방법으로 나와있습니다.

 

https://github.com/konvajs/react-konva/issues/588

 

Error when importing in Next.js · Issue #588 · konvajs/react-konva

I installed konva and react-konva to my next.js project. When I try to import anything from the react-konva package, I get this error Error: Must use import to load ES Module: C:\Users\bucsa\dev\at...

github.com

 

해당 이슈를 확인했을 때 마음에 들었던 방법은 Next의 Dynamic을 이용하는 방법입니다. 그 이유는 Canvas의 width, height를 설정할 때에 window객체를 사용해야 하는데 그를 위해서는 SSR을 false로 해야하기 때문입니다.

 

따라서 다음과 같이 바꾸어서 사용할 수 있습니다.

import dynamic from 'next/dynamic';

const NoSSRComponent = dynamic(() => import('./Konva'), {
  ssr: false,
});

const KonvaComponent: React.FC = () => {
  return <NoSSRComponent />;
};

export default KonvaComponent;