shikijs / shiki

A beautiful yet powerful syntax highlighter
http://shiki.style/
MIT License
9.76k stars 356 forks source link

Hugo website installation #495

Closed c2tz closed 1 year ago

c2tz commented 1 year ago

has anyone tried to install Shiki on a Hugo site ? Because I don't really know how to do it myself.

orta commented 1 year ago

Don't know anything about hugo other than it comes from the go ecosystem, think you might need to learn how it can interact with JS tools and get back to us

c2tz commented 1 year ago

Ok, so i've found something i don't know if that the best solution but that work :

  1. Create an extend_footer.html file in /layout/partial/
  2. Add this JS :
<script>
  document.addEventListener("DOMContentLoaded", async function() {
    const elements = document.querySelectorAll("pre code");
    const highlighter = await shiki.getHighlighter({
      theme: "dark-plus",
      langs: ["bat", "xml", "bash", "yml", "powershell"], // limit coloring to these
      loadTheme: () => import("shiki/themes/dark-plus.json")
    });

    elements.forEach(element => {
      const code = element.textContent;
      const language = element.className.replace("language-", "");
      const html = highlighter.codeToHtml(code, language);
      element.innerHTML = html;
    });
  });
</script>
  1. Create an extend_header.html file in /layout/partial/
  2. Add this content in the top of the file :
{{ if and (not (eq .Kind "home"))  (not (eq .Title "Search")) (not (eq .Title "404 Page not found")) }}
<script src="https://cdn.jsdelivr.net/npm/shiki" defer></script>
{{ end }}

I add {{ if and (not (eq .Kind "home")) (not (eq .Title "Search")) (not (eq .Title "404 Page not found")) }} as a precaution to avoid this throw on pages where there's normally no code to color.

I don't know if this solution is very clean, but it works for my use. I haven't noticed any significant performance problems apart from onig.wasm, but that's the price we have to pay to get the best syntax coloring for our code.

orta commented 2 months ago

I also did this a bit later, but via post-processing the built files: https://blog.puzzmo.com/posts/2024/06/23/shiki-hugo/

c2tz commented 2 months ago

thank you @orta, that's a good way to do it. for my part, i'm now using material for mkdocs (because it's infinitely more complete, although less customizable). i haven't thought about integrating shiki yet, but if you ever use it on it, i'd love to.