avatar

Tetsuya Ohira's Blog

Software Developer in Japan 🚀

コードブロックのシンタックスハイライト対応しました

2023-03-19

このブログのコードブロックのシンタックハイライト対応を行いました。

Before

before

After

after

手順

1. 必要なライブラリをインストール

npm install react-markdown npm install react-syntax-highlighter

2. コンポーネントでimportする

import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'
  • Prismの方が機能が多いのでPrismを使用する
import { vscDarkPlus } from 'react-syntax-highlighter/dist/cjs/styles/prism'
  • 公式サイトの通りに、import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism'と書くとエラーになるので、cjsを使用する
  • vscDarkPlusは、Visual Studio CodeDark+テーマ
  • 他のテーマはこちら

3. ReactMarkdownタグを追加

export default function Post({ postData }) { return ( <Layout> <Head> <title>{postData.title}</title> </Head> <article className="p-10"> <h1 className="text-3xl font-bold">{postData.title}</h1> <div className="mt-5 text-gray-500">{postData.date}</div> <ReactMarkdown className="prose mt-5" components={{ code({ node, inline, className, children, ...props }) { const match = /language-(\w+)/.exec(className || '') return !inline && match ? ( <SyntaxHighlighter style={vscDarkPlus} language={match[1]} PreTag="div" {...props} > {String(children).replace(/\n$/, '')} </SyntaxHighlighter> ) : ( <code className={className} {...props}> {children} </code> ) }, }} > {postData.markdown} </ReactMarkdown> </article> </Layout> ) }
  • ReactMarkdownタグの中に{postData.markdown}を記述する
  • 公式サイトの通りに、children={postData.markdown}のようにpropsとして渡すと、ESLint: Do not pass children as props. Instead, nest children between the opening and closing tags.(react/no-children-prop)エラーが発生するので、ReactMarkdownタグに{postData.markdown}を挟む
  • SyntaxHighlighterについても同様に、SyntaxHighlighter要素でコードブロックをを挟む

参考