LoginSignup
10
5

More than 3 years have passed since last update.

【TypeScript】マークダウン文字列をHTMLにパースする(GitHub Flavored Markdown)

Last updated at Posted at 2019-12-01

使用するモジュール

  • marked, @types/marked
    markdownをHTMLにパース

  • highlight.js,@types/highlight.js
    コードのシンタックスハイライト部分をパース
    highlightjsモジュールも存在しますが、別物なので間違えないように注意

npm i marked @types/marked highlight.js @types/highlight.js

サンプルコード

import marked      from 'marked';
import highlightjs from 'highlight.js';

marked.setOptions({
  highlight: function(code, lang) {
    return highlightjs.highlightAuto(code, [lang]).value;
  },               // シンタックスハイライトに使用する関数の設定
  pedantic: false, // trueの場合はmarkdown.plに準拠する gfmを使用する場合はfalseで大丈夫
  gfm: true,       // GitHub Flavored Markdownを使用
  breaks: true,    // falseにすると改行入力は末尾の半角スペース2つになる
  sanitize: true,  // trueにすると特殊文字をエスケープする
  silent: false    // trueにするとパースに失敗してもExceptionを投げなくなる
});

const markdown: string = `
# Hello World

\`\`\`ruby
puts 'Hello World'
\`\`\`

<h1>Hello World</h1>
`

const html: string = marked(markdown)
console.log(html);
/* =>
 * <h1 id="hello-world">Hello World</h1>
 * <pre><code class="language-ruby">puts <span class="hljs-string">'Hello World'</span></code></pre>
 * <p>&lt;h1&gt;Hello World&lt;/h1&gt;
 * </p>
 */

参考

10
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
5