Next.jsでMarkdownエディタを使用する

9691 ワード

現在、ブログを直接表現する個人的なプロジェクトが行われています.
しかしmarkdown editorを使うのは簡単ではないので、私が実現したコードをここに書きたいです.

ライブラリの選択


タグ付き編集候補
  • https://www.npmjs.com/package/@toast-ui/editor
  • https://www.npmjs.com/package/@uiw/react-md-editor
  • 比較


    デザイン
  • トースト:華やかで便利なデザインが多い
  • uiw:デザインがあっさりしていて機能も少ない
  • 下り数(2022年3月)
  • トースト:7.6万.たゆまぬ努力
  • uiw:1.3万.しかし最近は上昇傾向にある
  • 正式な書類
  • トースト:一般的なものに比べて公式文書が不親切
  • uiw:使用例ごとに独自のマニュアル、話題整理がある
  • 構文
  • トースト:文法が不便.refを上手に活用すること
  • uiw:文法直観
  • n/a.結論


    @uiw/react-md-editorに決めました!
  • 個人的なプロジェクトですので、開発が便利であることが重要です
  • 私の好みでUIが決まるので、それほど目立たないデザインが重要です.
  • なるべく文章を簡略化するつもりなので、機能の利便性は重要ではない
  • インプリメンテーションコード

    yarn add next-remove-imports @uiw/[email protected]
  • components/organisms/Editor.tsx
  • import {MDEditorProps} from "@uiw/react-md-editor";
    import dynamic from "next/dynamic";
    import "@uiw/react-md-editor/markdown-editor.css";
    import "@uiw/react-markdown-preview/markdown.css";
    
    const MDEditor = dynamic<MDEditorProps>(() => import("@uiw/react-md-editor"), {
      ssr: false,
    });
    
    export type EditorProps = MDEditorProps
    
    export const Editor = ({
      ...rest
    }:MDEditorProps)=> {
      return (
        <MDEditor
          {...rest}
          />
      )
    }
  • pages/draft
  • import type {NextPage} from "next"
    import {useCallback, useState} from "react"
    import {Editor} from "components/organisms/Editor";
    
    type DraftPageProps = {
    }
    
    const DraftPage: NextPage<DraftPageProps> = ({
    
    }) => {
      const [value, setValue] = useState("**Hello world!!!**")
    
      const handleChange = useCallback((value)=>{
        setValue(value)
      },[])
    
      return (
        <div>
          <Editor
            value={value}
            onChange={handleChange}
            />
        </div>
      )
    }
    export default DraftPage
  • next.config.js
  • /** @type {import('next').NextConfig} */
    const nextConfig = {
      reactStrictMode: true,
    }
    
    // ref: https://uiwjs.github.io/react-md-editor/#support-nextjs
    const removeImports = require("next-remove-imports")();
    
    module.exports = removeImports(nextConfig)

    references

  • https://uiwjs.github.io/react-md-editor/#support-nextjs