@svelte-put/preprocess-auto-slug GitHub

svelte preprocessor to add id attribute and anchor tag

@svelte-put/preprocess-auto-slug @svelte-put/preprocess-auto-slug @svelte-put/preprocess-auto-slug changelog

Migrating to Svelte 5? See the new docs site here.

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:

  • search for matching elements (heading elements by default),

  • generate id attributes from element content,

  • add anchor tag to element.

preprocess-auto-slug alone is not that interesting. When paired with @svelte-put/toc (runtime logics), however, they provide a minimal and efficient solution for generating table of contents.

Installation

npm install --save-dev @svelte-put/preprocess-auto-slug
pnpm add -D @svelte-put/preprocess-auto-slug
yarn add -D @svelte-put/preprocess-auto-slug

Setup

Given the following config…

import autoSlug from '@svelte-put/preprocess-auto-slug';

/** @type {import('@sveltejs/kit').Config} */
const config = {
  preprocess: [autoSlug()],
};

export default config;

…and the following source code…

<h2>Quick start</h2>

preprocess-auto-slug will generate the following HTML:

<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 are generated, or the placement of the anchor tag. To avoid being verbose, utilize language server during development or see the type definitions here for more details.

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 new Array(2) as _, index}
  <h2 id="section-heading-{index}">Section Heading {index}</h2>
{/each}
<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>

Link from the Legend of Zelda series, with text saying 'don't click on any suspicious links'

Happy slugging! 👨‍💻

Edit this page on Github