A custom Remark plugin that creates Table of Contents (Toc).
npm install @sveltek/remark-tocA custom Remark plugin that creates Table of Contents (Toc).
> [!NOTE]
>
> While the API is solid and mostly complete, some changes may still occur before the first stable release.
>
> Ideas, suggestions and code contributions are welcome.
>
> If you find any issues or bugs, please report them so the project can be improved.
- Automatically adds links with attributes to the headings
- Stores Toc items to frontmatter for easy access
``sh`via pnpm
pnpm add -D @sveltek/remark-toc
`sh`via npm
npm install -D @sveltek/remark-toc
`ts
import { svelteMarkdown } from '@sveltek/markdown'
import { remarkToc } from '@sveltek/remark-toc'
svelteMarkdown({
plugins: {
remark: [[remarkToc, options]],
},
})
`
`ts
import { svelteMarkdown } from '@sveltek/markdown'
import { remarkToc } from '@sveltek/remark-toc'
svelteMarkdown({
layouts: [
{
name: 'layout-name',
path: 'path/to/custom/file.svelte',
plugins: {
remark: [[remarkToc, options]],
},
},
],
})
`
`ts
import { svelteMarkdown } from '@sveltek/markdown'
import { remarkToc } from '@sveltek/remark-toc'
svelteMarkdown({
entries: [
{
name: 'entry-name',
path: 'path/to/custom/file.svelte',
plugins: {
remark: [[remarkToc, options]],
},
},
],
})
`
Import and pass the plugin directly into the array.
`ts
import { svelteMarkdown } from '@sveltek/markdown'
import { remarkToc } from '@sveltek/remark-toc'
svelteMarkdown({
plugins: {
remark: [remarkToc],
},
})
`
It is also possible to further customize the plugin as needed.
`ts
import { svelteMarkdown } from '@sveltek/markdown'
import { remarkToc, type RemarkTocOptions } from '@sveltek/remark-toc'
const remarkTocOptions: RemarkTocOptions = {
depth: 4, // Specifies the maximum headings depth to be included in the table of content
links: false, // Specifies whether headings include link tags
}
svelteMarkdown({
plugins: {
remark: [[remarkToc, remarkTocOptions]],
},
})
`
After installation and setup, access the toc array from frontmatter data.
Keep in mind that this depends on how you load your markdown pages and may vary from project to project.
Here is a simple example of a Toc.svelte component that gets page data from a parent layout and generates it within a template.
`svelte
{#if toc}
Or use it directly within markdown pages.
`md
---
title: Blog page
description: Read the latest news.
---
{#each frontmatter.toc as toc}
- {toc.value}
{/each}
`API
$3
- Type:
TocItem[]`ts
interface TocItem {
id: string
depth: number
value: string
}
`Options
$3
- Type:
number
- Default: 3Specifies the maximum headings depth to be included in the table of content.
`ts
{
depth: 3,
}
`$3
- Type:
boolean
- Default: trueSpecifies whether headings include link tags.
`ts
{
links: true,
}
``Developed in ðŸ‡ðŸ‡· Croatia, © Sveltek.
Released under the MIT license.