Cover Image for rehypeで生成したhtmlでiframeが表示されるようにする

rehypeで生成したhtmlでiframeが表示されるようにする

概要

markdownからrehypeで生成したhtmlには直接記述したiframeが表示されない。 CodePenなどのEmbedをiframeで行いたい時に不便なので、解決する

結論

  • rehype-rawを使えばいい

ボツ案: ~~parse と stringify で htmlタグを表示されるようにする~~

import { rehype } from 'rehype'  
import rehypeHighlight from 'rehype-highlight'  
import rehypeStringify from 'rehype-stringify'  
import remarkParse from 'remark-parse'  
import remarkRehype from 'remark-rehype'  
  
export default async function markdownToHtml(markdown: string) {  
  const result = await rehype()  
    .use(remarkParse)  
    .use(remarkRehype, {  
      allowDangerousHtml: true  
	})  
    .use(rehypeHighlight)  
    .use(rehypeStringify, {  
      allowDangerousHtml: true  
	 })  
    .process(markdown)  
  return result.toString()  
}

parse と strigify に allowDangerousHtml: true を設定することで、表示されるようになるただし他のタグも表示されてしまうので、表示確認がちゃんと必要になる

流石にこれだと危なすぎるのでボツ

採用:rehype-raw を使う

流石にこんな危ない方法しかないわけないだろと思って ドキュメントを読んだらちゃんと書いてあった。rehype-raw を使えばいいらしい。 ~~最初からちゃんとドキュメント読んでないのがそもそも悪いのでは~~

こんな感じにすると良い

import { rehype } from 'rehype'  
import rehypeHighlight from 'rehype-highlight'  
import rehypeRaw from 'rehype-raw'  
import rehypeStringify from 'rehype-stringify'  
import remarkParse from 'remark-parse'  
import remarkRehype from 'remark-rehype'  
  
export default async function markdownToHtml(markdown: string) {  
  const result = await rehype()  
    .use(remarkParse)  
    .use(remarkRehype, { allowDangerousHtml: true })  
    .use(rehypeRaw)  
    .use(rehypeHighlight)  
    .use(rehypeStringify)  
    .process(markdown)  
  return result.toString()  
}