70 %

Enabling all languages in prism-react-renderer using a custom Prism instance


In my previous post I moved syntax highlighting to build-time on my Toast powered site. This was great as it removed the runtime dependencies of prismjs, prism-react-renderer, etc. One problem was that I started writing Haskell and Rust posts and neither of these languages are included by default, so I had to include them. In this case I chose to include all of the languages prism offers (except meta which fails for unknown reasons).

prebuild.js
JS
const Highlight = require("prism-react-renderer");
const Prism = require("prismjs");
const loadLanguages = require("prismjs/components/index");
const prismComponents = require("prismjs/components");
try {
// meta doesn't exist in the prismjs package and thus will *FAIL* because it's a FAILURE
loadLanguages(
Object.keys(prismComponents.languages).filter(v => v !== "meta")
);
} catch (e) {
// this is here in case prismjs ever removes a language, so we can easily debug
console.log(e);
}

After loading the languages, you need to pass the custom Prism instance into Highlight as a prop when you render, and you have access to all of the languages. Remember this is done at build time, so we don't have to worry about file sizes.

JS
<Highlight Prism={Prism}/>