🍄

Laravel+Vueでマークダウンを取り扱う

に公開

環境

  • Laravel + Inertia
  • Vue3
  • markdown-it
  • highlight.js

想定

【保存】

  1. フロントエンドでマークダウンテキストを入力
  2. バックエンドにマークダウンテキストを送信
  3. バックエンドでサニタイズ
  4. DBに保存

【表示】

  1. バックエンドからマークエンドを取得
  2. フロントエンドでマークアップ

必要パッケージのインストール

npm install markdown-it
npm install highlight.js

markdown-it

const ticket_description = computed(function () {
  const md = markdownit()
  return md.render(props.ticket.description);
});

HTMLが文字列として表示されている状態

これは {{ticket_description}} で表示しているのが悪かったので <div v-html="ticket_description"> に修正

CSSがシンプルな状態

なんでこんなシンプルになってるのかと思ったらデフォでreset.css的なものが当たっているらしい

対応

npm install @tailwindcss/typography

app.css に追加

@import 'tailwindcss';
+@plugin "@tailwindcss/typography";
@import 'tw-animate-css';

黒背景にグレーの文字とかいう大変見づらい状態

めんどくさいので終わっていいかな。ライトモードの時は問題ないし……

highlight.js

Syntax highlighting

import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'
const markup = computed(function () {
  const md = markdownit({
    highlight: function (str: string, lang: string) {
      if (lang && hljs.getLanguage(lang)) {
        try {
          return '<pre><code class="hljs">' +
            hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
            '</code></pre>';
        } catch (__) { }
      }

      return '<pre><code class="hljs">' + md.utils.escapeHtml(str) + '</code></pre>';
    }
  });
  return md.render(props.markdown);
});

コードブロックにハイライトが入った様子

よろしい

GitHubで編集を提案

Discussion