Movatterモバイル変換


[0]ホーム

URL:


@svelte-put/preprocess-auto-slug

GitHubGithub

svelte preprocessor to add id attribute and anchor tag

Compatible with or powered directly bySvelte runes.

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

Still on Svelte 4? Seethe old docs site here.

Introduction

This package is heavily inspired byrehype-slug andrehype-autolink-headings. If you are already using a markdown preprocessor such asMDsveX with some otherrehype plugins,rehype-slug andrehype-autolink-headings should already work well.

preprocess-auto-slug operates atbuild time and does the following:

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

  • generateid 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 ofpreprocess-auto-slug can be customized, including which tags to process, howid andhref are generated, or the placement of the anchor tag. To avoid being verbose, utilize language server during development or see thetype definitions here for more details.

This documentation site uses this very package. Mostid and link tag for headings are auto-generated during build. Seesvelte.config.js as an example for a more complex use case.

Limitation

preprocess-auto-slug will generate duplicatedid for matching nodes rendered insideeach block. In such cases it is recommended to manually specifyid 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


    [8]ページ先頭

    ©2009-2025 Movatter.jp