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

highlight.jsをファイル読み込みで読み込んだコードに使ってみる

Last updated at Posted at 2025-06-13

はじめに

 コードハイライトのライブラリであるhighlight.jsを使ってみる。

適用するのはネット上の、自作ライブラリのコード。

ちょっとしたツールボックス。

つかいかた

 ここに詳しく書いてある。

CDNを使おうと思う。

コード全文

<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Code Highlight</title>
    <link rel="stylesheet" href="style.css" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.11.1/build/styles/base16/oceanicnext.min.css" /> <!-- パレット -->
    <script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.11.1/build/highlight.min.js"></script> <!-- 生成機 -->
    <style>
      /* カスタマイズは自由自在。 */
      .hljs-comment{
        color:aquamarine;
      }
    </style>
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link href="https://fonts.googleapis.com/css2?family=Inconsolata:wght@200..900&display=swap" rel="stylesheet" />
  </head>
  <body>
    <pre><code class="javascript" id="target-tag">
</code></pre>
    <!--<script>hljs.highlightAll();</script>-->
    <script src="main.js"></script>
  </body>
</html>
main.js
async function getText(url){
  // text string
  const response = await fetch(url);
  if(!response.ok){
    throw new Error(`response.status: ${response.status}`);
  }
  const txt = response.text(); // テキストデータが欲しい時はこれ
  return txt;
}

getText("https://inaridarkfox4231.github.io/fisceToyBox/fisceToyBox.js").then((res) => {
  const codeDom = document.getElementById("target-tag");

  res = res.replaceAll('&', '&amp;');
  res = res.replaceAll('<', '&lt;');
  res = res.replaceAll('>', '&gt;');
  res = res.replaceAll('"', '&quot;');
  res = res.replaceAll("'", '&apos;');

  codeDom.innerHTML = res;

  hljs.highlightElement(codeDom);
});
style.css
code {
  font-family: Inconsolata;
  line-height:130%;
  font-size:18px;
  margin:0;
}

結果(一部)

wqswc2wc.png

解説

 コードのフォントは人気のInconsolataで、Google fontの一種で、こっちから使える:

テーマはたくさんあり、ここで選ぶことができる:

自分はoceanicnextが気に入ったのでこれを使ってる。demoのうちbase16とあるものは、コードにもあるようにbase16をはさんで指定する。最後にminを付けるのを忘れずに。ここから取ってるらしい:

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.11.1/build/styles/base16/oceanicnext.min.css"> <!-- パレット -->
    <script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.11.1/build/highlight.min.js"></script> <!-- 生成機 -->

そのあとスクリプトを埋め込んでいる。このときhljsがグローバルになり、いろいろ呼び出すことができる。

 なお、oceanicnextはコメントアウトが見えづらかったのでそこだけカスタマイズさせていただいてる:

    <style>
      /* カスタマイズは自由自在。 */
      .hljs-comment{
        color:aquamarine;
      }
    </style>

直接埋め込んでもいいが、今回は読み込んだファイルを使いたいので、スクリプトでコードを入れてから関数で動的にハイライトを掛けている。

async function getText(url){
  // text string
  const response = await fetch(url);
  if(!response.ok){
    throw new Error(`response.status: ${response.status}`);
  }
  const txt = response.text(); // テキストデータが欲しい時はこれ
  return txt;
}

この関数で非同期的にテキストデータを取得できる。jsでも、htmlでも、cssでも、何でも。
これを次のようにプロミスでinnerHTMLにセットして、highlightElementで動的にハイライトする。

getText("https://inaridarkfox4231.github.io/fisceToyBox/fisceToyBox.js").then((res) => {
  const codeDom = document.getElementById("target-tag");

  res = res.replaceAll('&', '&amp;');
  res = res.replaceAll('<', '&lt;');
  res = res.replaceAll('>', '&gt;');
  res = res.replaceAll('"', '&quot;');
  res = res.replaceAll("'", '&apos;');

  codeDom.innerHTML = res;

  hljs.highlightElement(codeDom);
});

なお、その際にエスケープシーケンスによる置き換え処理を実行している。実はなくてもうまくいくようになっているが、その場合セキュリティエラーを出されてしまう。試しにこれらすべてをコメントアウトすると:

adqdw.png

このように変換はうまくいくがエラーを食らう。なのでなるべくなら変換した方がよい。

直接ハイライトする場合

 ファイルを読み込まずに直接ハイライトする場合は、普通に書けばいい。

  <body>
    <pre><code class="javascript" id="target-tag">console.log("hello, world!");
const p = (2 < 3) && (4 > 1);
</code></pre>
    <script>hljs.highlightAll();</script>
    <!--<script src="main.js"></script>-->
  </body>

結果:

qfwqcwv.png

この場合もエスケープは不要だが、エスケープしても同じ結果にはなる。

  <body>
    <pre><code class="javascript" id="target-tag">console.log("hello, world!");
const p = (2 &lt; 3) &amp;&amp; (4 &gt; 1);
</code></pre>
    <script>hljs.highlightAll();</script>
    <!--<script src="main.js"></script>-->
  </body>

結果:同じ

なお、当然だがhtmlでこんなことをすればエラーを食らうし、正常な結果にならない。

  <body>
    <pre><code class="html" id="target-tag"><p>こんにちは!せかい!</p>
</code></pre>
    <script>hljs.highlightAll();</script>
    <!--<script src="main.js"></script>-->
  </body>

結果:

fswgvwvev.png

エスケープしましょう。

  <body>
    <pre><code class="html" id="target-tag">&lt;p&gt;こんにちは!せかい!&lt;/p&gt;
</code></pre>
    <script>hljs.highlightAll();</script>
    <!--<script src="main.js"></script>-->
  </body>

結果:

wwfwfw.png

おわりに

 コードハイライトにはいろんな方法があるようです。今回はテーマの豊富さからこれを選びました。次の記事は非常に参考になりました。ありがとうございます。

拝読感謝。

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