logikfabrik

How to use highlight.js language definitions with lowlight

1 min read

lowlight is a syntax highlighter for virtual DOMs with support for highlight.js language definitions.

For this example we add XML support to lowlight, using the XML language definition bundled with highlight.js.

Install the packages:

npm i lowlight highlight.js
npm i --D @types/lowlight

And add XML support:

import low from "lowlight/lib/core";
//import hljs from "highlight.js";
import xml from "highlight.js/lib/languages/xml";

low.registerLanguage("xml", xml);

The import highlight.js/lib/languages/xml will give the following warning (TS7016):

Could not find a declaration file for module 'highlight.js/lib/languages/xml'

This warning has to do with how modules are/were declared in highlight.js index.d.ts. Uncomment the import highlight.js, or in tsconfig.json, add highlight.js to types1:

{
  "compilerOptions": {
    "types": ["highlight.js"]
  }
}

For this next example we add Razor support to lowlight, using the 3rd party package highlightjs-cshtml-razor.

Install the packages:

npm i lowlight highlightjs-cshtml-razor
npm i --D @types/lowlight

Add a .d.ts declaration file for highlightjs-cshtml-razor:

declare module "highlightjs-cshtml-razor" {
  export = function (hljs): void {};
}

And add Razor support:

import hljs from "lowlight";
import hljsDefineCshtmlRazor from "highlightjs-cshtml-razor";

hljsDefineCshtmlRazor(hljs);

Done!


  1. Option to add packages to the global scope. See the tsconfig.json reference.