GeoffSelby / tailwind-highlightjs

Bake highlight.js themes directly into your Tailwind Css build.
MIT License
23 stars 1 forks source link

In/Exclude languages #6

Closed Toemsel closed 1 year ago

Toemsel commented 1 year ago

The entire bundle for the highlighjs is over 1MB., although I would only need two languages. How can one provide a whitelist of languages to include?

Toemsel commented 1 year ago

Found the solution. Installed the dependencies

npm install highlight.js --save npm install @types/highlight.js --save-dev

Create a file to include all the languages you want to

import hljs from "highlight.js/lib/core";
import javascript from "highlight.js/lib/languages/javascript";
import csharp from "highlight.js/lib/languages/csharp";
import bash from "highlight.js/lib/languages/bash";
import c from "highlight.js/lib/languages/c";
import cpp from "highlight.js/lib/languages/cpp";

hljs.registerLanguage('javascript', javascript);
hljs.registerLanguage('csharp', csharp);
hljs.registerLanguage('bash', bash);
hljs.registerLanguage('c', c);
hljs.registerLanguage('cpp', cpp);

export function highlight(code: string, lang: string): string {
    return hljs.highlight(code, { language: lang }).value;
}

Import that file and use it just like that

import { highlight } from "@/THE_HIGHLIGHT_FILE";

marked.setOptions({
  highlight: function (code, lang) {
    try{
      return highlight(code, lang);
    }
    catch {
      return code;
    }
  },
});