Skip to content

Commit ed7f949

Browse files
committed
Add code highlighting
1 parent e951a8e commit ed7f949

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/highlightCode.test.ts

Whitespace-only changes.

src/highlightCode.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import hljs from 'highlight.js'
2+
import * as cheerio from 'cheerio'
3+
4+
/*
5+
* Highlight code blocks in page
6+
*
7+
* @param $page - Cheerio object
8+
*/
9+
export async function highlightCode($page: cheerio.CheerioAPI): Promise<void> {
10+
const $elements = $page('pre code')
11+
$elements.each((i, $e) => {
12+
if(
13+
!$e.attribs.class.startsWith('yaml') &&
14+
!$e.attribs.class.startsWith('json')
15+
) {
16+
return
17+
}
18+
19+
console.log(`Highlighting code block: ${i}`)
20+
console.log($page($e).text())
21+
// Inserting the hljs class gets us the AWS CSS formatting we want.
22+
const text = $page($e).addClass('hljs').text()
23+
24+
let highlightedCode = ''
25+
if ($e.attribs.class.startsWith('json')) {
26+
highlightedCode = hljs.highlight(text, { language: 'json' }).value
27+
} else if ($e.attribs.class.startsWith('yaml')) {
28+
highlightedCode = hljs.highlight(text, { language: 'yaml' }).value
29+
}
30+
31+
$page($e).html(highlightedCode)
32+
})
33+
}

0 commit comments

Comments
 (0)