Skip to content

Transformers

Shikiji uses 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')
},
span
(
node
,
line
,
col
) {
node
.
properties
['data-token'] = `token:${
line
}:${
col
}`
}, }, ] })

We also provide some common transformers for you to use, see shikiji-transforms for more details.

codeToHast

You can also get the intermediate hast to do custom rendering without serializing them into HTML with codeToHast. You can also further integrate the AST with 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' } ]
                }
              ]
            }
          ]
        }
      ]
    }
  ]
}

Released under the MIT License.