Skip to content

Instantly share code, notes, and snippets.

@lightpohl
Last active February 17, 2024 23:06
Show Gist options
  • Save lightpohl/f7786afa86ff2901ef40b1b1febf14e0 to your computer and use it in GitHub Desktop.
Save lightpohl/f7786afa86ff2901ef40b1b1febf14e0 to your computer and use it in GitHub Desktop.
Use marked and prism.js to parse markdown and add syntax highlighting in Node.js
// Versions: marked v0.6.2, prismjs v1.15.0
let marked = require('marked');
let prism = require('prismjs');
let loadLanguages = require('prismjs/components/');
loadLanguages(['javascript', 'jsx', 'css', 'markup', 'bash', 'json']);
marked.setOptions({
highlight: function(code, lang) {
if (prism.languages[lang]) {
return prism.highlight(code, prism.languages[lang], lang);
} else {
return code;
}
}
});
let someMarkdown = "```javascript\nlet x = 2;```";
let html = marked.parse(someMarkdown)
@diegozanon
Copy link

Worked fine! Thanks! Just made a small change: used loadLanguages() with no parameters so all of them were loaded and I don't need to worry about which languages I may need in the future.

@rahuldahal-zz
Copy link

@lightpohl
Now the library says, "loadLanguages is not a function"

@NoelTheis
Copy link

NoelTheis commented Nov 8, 2021

For me at least, the example was not working because marked does not seem to recognize ```javascript\nlet x = 2;``` as a proper code block?
It only works for me with a line break before the closing "```" : ```javascript\nlet x = 2;\n```

Leaving this in case someone else stumbles upon this

@lai32290
Copy link

lai32290 commented Mar 7, 2022

Thanks! it works!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment