javascript/사이드 프로젝트

Next.js 에 toast ui Editor 을 같이 사용하는 방법 (짱쉬움)

윤-찬미 2021. 4. 6. 20:53

next.js 에 tui Editor을 쓰고자 하시는 분들께 도움이 되길 바랍니다!

기본적으로 next.js를 쓴다는건 ssr을 하겠다는 이야기 인데 tui Editor에서는 ssr을 지원하지 않습니다.

(딱히 지원할 이유도 없구요)

그렇기에 이둘을 같이 쓰게 되면 아래와 같이 window is not defined 라고 에러가 뜹니다.

이유는 window 객체는 client-side에서만 존재하는데 server-side에서 먼저 실행되기에

window 객체가 없다는 에러가 뜨는 것이지요. 즉 브라우저에서만 작동되기 때문입니다.

 

With no SSR

자 그러면 에디터가 나오는 부분은 ssr을 하지 않아주도록 합시다.

공식문서를 보면 모듈에 브라우저에서만 작동하는 라이브러리가 들어있는 경우엔

서버측에 모듈을 포함하지 않고 싶을 것이니,

우리가 dynamic import를 지원해주겠다고 나와있습니다. (nice 짱편함)

nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr

 

Advanced Features: Dynamic Import | Next.js

Dynamically import JavaScript modules and React Components and split your code into manageable chunks.

nextjs.org

문서에 보시면 위와 같이 설명이 참조가 되어있습니다.

저 문서를 같이 보면서 해결해 보도록 합시다!

우선 에디터 컴포넌트를 하나 만들어줍니다.

import { Editor } from '@toast-ui/react-editor';

import 'codemirror/lib/codemirror.css';
import '@toast-ui/editor/dist/toastui-editor.css';

function PostEditor():JSX.Element {
  return (
    <Editor 
      initialValue="hello react editor world!"
      previewStyle="vertical"
      height="600px"
      initialEditType="markdown"
      useCommandShortcut={true}
    />
  );
}

export default PostEditor;

 

그 후 이 컴포넌트를 사용하는 쪽에서 아래와 같이 임포트 하여 사용하면 됩니다.

import dynamic from 'next/dynamic';

const PostEditor = dynamic(
  () => import('../components/writePost/PostEditor'),
  { ssr: false }
)

function writePost():JSX.Element {
  return (
    <>
      <PostEditor />
    </>
  )
}

export default writePost;

 

너무 쉽고 간단하게 해결 할 수 있습니다.

낼은 저 다이나믹 코드를 한번 뜯어 봐야겠습니다. (신난당)