@svelte-put/preprocess-auto-slug
svelte preprocessor to add id attribute and anchor tag
Introduction
This package is heavily inspired by
rehype-slug
and
rehype-autolink-headings . If you are already using
MDsveX with some other rehype
plugins,
rehype-slug
and rehype-autolink-headings
should already work well.
preprocess-auto-slug
operates at build time and does the following:
1
Search for matching elements (heading elements by default),
2
Generate
id
attributes from element content,3
add anchor tag to element.
preprocess-auto-slug
alone is not that interesting. When coupled with
@svelte-put/toc (runtime logics), however, it provides a
minimal & efficient solution for generating table of contents.
Installation
terminal
npm install --save-dev @svelte-put/preprocess-auto-slug
Quick Start
Given the following input
quick start - input
<h2>Quick start</h2>
And the default config
svelte.config.js
import autoSlug from '@svelte-put/preprocess-auto-slug';
/** @type {import('@sveltejs/kit').Config} */
const config = {
preprocess: [autoSlug()],
};
export default config;
preprocess-auto-slug
will generate the output below
quick start - output
<h2 id="quick-start">
<a href="#quick-start" aria-hidden="true" tabindex="-1">#</a>
Quick Start
</h2>
Customization
Almost every aspect of preprocess-auto-slug
can be customized, including which tags
to process, how id
and href
is generated, or the placement of the anchor
tag.
For more details, inspect in-code documentation, read the API Reference , and check out the default options .
This documentation site uses this very package. Most id
and link tag for headings are auto-generated during build. See svelte.config.js
as an example for a more complex use case.
Limitation
preprocess-auto-slug
will generate duplicated id
for matching nodes
rendered inside each
block. In such cases it is recommended to manually specify
id
for the node.
each block - input
{#each new Array(2) as _, index}
<h2 id="section-heading-{index}">Section Heading {index}</h2>
{/each}
each block - output
<h2 id="section-heading-0">
<a href="#section-heading-0" aria-hidden="true" tabindex="-1">#</a>
Section Heading 0
</h2>
<h2 id="section-heading-1">
<a href="#section-heading-1" aria-hidden="true" tabindex="-1">#</a>
Section Heading 1
</h2>
Happy slugging! 👨💻