简体   繁体   中英

Javascript library for code syntax highlighting

I came across Syntax highlighting code with Javascript , which explains very well how to do syntax highlighting on the client side.

Right now, I'm scraping sites and would like to do the syntax highlighting on the server side, as I'm scraping. We're using node.js cheerio to get some of the basic jQuery features as we're scraping. Is there a simple javascript library that works with cheerio (not a full-fledged jQuery) that lets me do something along the lines of:

var highlightedCode = JsCodeSyntaxHighlighter.highlightCode(...);

where... is raw HTML.

Or, can I accomplish that with prettify or jQuery syntax highlighter (ie does jQuery syntax highlighter only rely on functionality that cheerio provides?).

The reason I need to do this server-side and not client-side is because we load thousands of code divs on the client at once (mostly hidden, but still), and running jQuery syntax highlighter on thousands of snippets takes a few seconds, which is too slow.

you can use prettier.

requirements

const chreerio=require("cheerio"),
prettier=require("prettier")
$=cheerio.load(`<ul id="fruits"><li class="apple">Apple</li><li class="orange">Orange</li><li class="pear">Pear</li>
</ul>`)
var response = prettier.format($.root(), {  parser: "html" });
console.log(response);

Additionally In production, formatting code on the server side is a bad idea.

This will increase the content size and will take more inte.net to load the page.

And also Why do you need to format the code?

Don't know if this is what you want, but on my blog I use Alex Gorbatchev's Syntax Highlight which is pretty awesome. It's javascript, but I use it as a client side script. I've never used server side JS (read NodeJS) and I don't know how compatible they can be, but you should give it a shot and see if you like it.

Hope I can help!

There are many libraries to do this like rainbowjs, highlightjs, prismjs, etc. All of these provide custom spans and default spans for popular languages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM