TOC - Table of Contents

The default "remark-toc" plugin may not generate a TOC for markdown files that are imported as Svelte components. To address this limitation, you can use a built-in function provided by the "mdx-svelte" package.

Example usage

+layout.svelte:

<script lang="ts">
    import { makeToc } from "mdx-svelte"
 
    const headings = makeToc({
        container: ".my-markdown-container",
    })
</script>

Returns:

[{
    "level": "2", // or 3, 4, 5, 6
    "textContent": "Example usage",
    "attributes": { "id": "example-usage" }
}]

WARNING

When using this solution, remember to disable the "remark-toc" plugin.

How to disable "remark-toc" plugin?

import { unifiedTransformer } from "mdx-svelte/unified"
 
mdxPreprocess({
    onTransform: async (options, config) => {
        return await unifiedTransformer(options, config, {
            builtInPlugins: {
                remarkToc: {
                    enable: false,
                },
            },
        })
    },
})
Return to top