3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

highlight.jsとcheerioのバンドルサイズを削減した時の備忘録

Last updated at Posted at 2021-01-31

本記事は、highlight.jscheerioを使用した際にバンドルサイズが思ったより膨れ上がり、ダイエットさせた時の備忘録。

スクリーンショット 2021-01-31 14.37.11.png

膨れ上がった原因その1 

  • highlight.jsをそのままimportしていた。
import hljs from 'highlight.js'; 
...

この場合、highlight.jsが対応する各言語のモジュールが全てインポートされてしまう。

対応

特定の言語のみ記述・ハイライトすれば良いので、ニッチな言語のモジュールはバンドル対象外となるように必要な言語分だけインポートさせていく。

以下は、例としてJavascriptのみモジュールをインポートした時のコード。

import hljs from 'highlight.js/lib/core';
import javascript from 'highlight.js/lib/languages/javascript';

hljs.registerLanguage('javascript', javascript);

以下、特定言語(15種類ほど)のみインポートした時の、バンドルサイズを対応前と比較したレポート。

- 対応前 対応後
size(Gzipped) 265.84kb 133.91kb -131.93kb
analyze スクリーンショット 2021-01-31 15.00.10.png スクリーンショット 2021-01-31 15.01.22.png -

膨れ上がった原因その2 

  • cheerio使ってハイライト箇所を抽出していた

マークダウン形式のhtml情報から、コード箇所を抽出するために、以下のようにcherrioを使用して、html要素を書き変える実装をしていた。

const $ = cheerio.load(article.body);
$('pre code').each((_, elm) => {
    const result = hljs.highlightAuto($(elm).text());
    $(elm).html(result.value);
    $(elm).addClass('hljs');
});

body = $.html();

対応

highlight.jsの機能であるinitHighlighting()をクライアント側でhtmlのレンダリング時に、実行されておけばcherrioを使う必要がなかった。

そのため、こちらは削減というよりcherrioごと削除して対応した。

initHighlighting( )は、ページ内の全ての<pre><code>ブロックをハイライトする機能。

3
0
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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?