Transformers
Shikiji used hast
(a AST format for HTML) to process the result and generate the HTML.
You can provide your own transformers
to customize the generated HTML by manipulating the hast tree. You can pass custom functions to modify the tree for different types of nodes. For example:
ts
import { addClassToHast, codeToHtml } from 'shikiji'
const code = await codeToHtml('foo\bar', {
lang: 'js',
theme: 'vitesse-light',
transformers: [
{
code(node) {
addClassToHast(node, 'language-js')
},
line(node, line) {
node.properties['data-line'] = line
if ([1, 3, 4].includes(line))
addClassToHast(node, 'highlight')
},
token(node, line, col) {
node.properties['data-token'] = `token:${line}:${col}`
},
},
]
})
We also provide some common transformers for you to use, check shikiji-transforms
for more details.
codeToHast
You can also got the intermediate hast
to do your custom rendering without serialize them into HTML with codeToHast
. You can also further integrate the ast the unified ecosystem.
ts
const root = highlighter.codeToHast(
'const a = 1',
{ lang: 'javascript', theme: 'nord' }
)
console.log(root)
ts
{
type: 'root',
children: [
{
type: 'element',
tagName: 'pre',
properties: {
class: 'shiki vitesse-light',
style: 'background-color:#ffffff;color:#393a34',
tabindex: '0'
},
children: [
{
type: 'element',
tagName: 'code',
properties: {},
children: [
{
type: 'element',
tagName: 'span',
properties: { class: 'line' },
children: [
{
type: 'element',
tagName: 'span',
properties: { style: 'color:#AB5959' },
children: [ { type: 'text', value: 'const' } ]
},
{
type: 'element',
tagName: 'span',
properties: { style: 'color:#B07D48' },
children: [ { type: 'text', value: ' a' } ]
},
{
type: 'element',
tagName: 'span',
properties: { style: 'color:#999999' },
children: [ { type: 'text', value: ' =' } ]
},
{
type: 'element',
tagName: 'span',
properties: { style: 'color:#2F798A' },
children: [ { type: 'text', value: ' 1' } ]
}
]
}
]
}
]
}
]
}