highlight.js

Highlight.js not working with marked - returning TypeError: (e || "").toLowerCase is not a function


I'm using (client/browser side, not in Node):

and I'm having trouble with simple example from the docs - when the language is know the code breaks.

I have this code:

  const markedRenderer = new marked.Marked(
    markedHighlight.markedHighlight({
      langPrefix: 'hljs language-',
      highlight(code, lang) {
        if ( ['nohighlight', 'plaintext'].includes(('' + lang).trim())) {
          return code;
        } else {
          const language = hljs.getLanguage(lang);
          if (typeof language === 'undefined') {
            return hljs.highlightAuto(code).value;
          } else {
            console.log("highlighting", lang, language)
            return hljs.highlight(code, { language, ignoreIllegals: true }).value;
          }
        }
      }
    })
  );

First two branches work fine (plaintext and auto), but the last branch - when the language is known - breaks with the following message:

highlight.min.js:273 Uncaught (in promise) TypeError: (e || "").toLowerCase is not a function
Please report this to https://github.com/markedjs/marked.
    at v (highlight.min.js:273:33)
    at f (highlight.min.js:233:31)
    at Object.h [as highlight] (highlight.min.js:184:28)
    at Object.highlight (47153:1421:25)
    at R.walkTokens (index.umd.js:35:30)
    at n.walkTokens (Instance.ts:201:48)
    at R.walkTokens (Instance.ts:31:45)
    at R.parse (Instance.ts:253:26)
    at 47153:1567:33

The hljs.getLanguage(lang); works fine and console.log prints out:

highlighting C 
{
{name: 'C', aliases: Array(1), keywords: {…}, disableAutodetect: true, illegal: '</', …} aliases : ['h'] contains : (11) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}] disableAutodetect : true exports : {preprocessor: {…}, strings: {…}, keywords: {…}} illegal 
....

The code snippet in md is:

#include <stdio.h>
int main() {
  puts("hello"); 
  return 0;
}

So, esentially, when I delete the "C" the auto-highlight kicks-in and it works fine, but when the language is assigned it breaks.

What am I missing?

EDIT:

here is a pen: https://codepen.io/Igor-Mekterovi/pen/LYMOaGJ

Just delete the "C" in the line with four backticks, wait few seconds, and see that the highlightAuto works.


Solution

  • The error is this: on the line

    return hljs.highlight(code, { language, ignoreIllegals: true }).value;
    

    language is expected to be the language name (a string).

    However, hljs.getLanguage(lang) returns an object. This value that is an object but was expected to be a string is the minified e in the error message you get. The actual non-minified function is getLanguage, called from highlight.

    The solution is to replace the above mentioned line with something like:

    return hljs.highlight(code, {language: language.name, ignoreIllegals: true }).value;