Try out playground!

vite-plugin-svelte-docgen

NPM Version

This plugin creates virtual JavaScript modules with data generated by svelte-docgen for targeted component - on demand.

Installation

Use Node.js package manager of your choice. e.g.:

{@html
pnpm install --save-dev vite-plugin-svelte-docgen
}

Prerequisites

This package depends on the following packages (peer dependencies) to be existent in your project:

  • svelte
  • typescript
  • vite

Setup

Vite

Inside your Vite config:

{@html
import { defineConfig } from "vite";
import pluginSvelteDocgen from "vite-plugin-svelte-docgen";
//     πŸ‘† import this package - you can name it however you want

export default defineConfig({
  plugins: [
    // πŸ‘‡ Add to plugins list - there's no strict requirement on the order
    pluginSvelteDocgen(),
  ],
  // ...
});
}

TypeScript

There are two ways on how you can improve TypeScript experience.

Via tsconfig.json

{@html
{
  "compilerOptions": {
    // ... other options
    "types": [, /* other types */ "vite-plugin-svelte-docgen"],
  },
}
}

Using triple-slash directive

Either in global .d.ts file or each individual JavaScript/TypeScript file, add at the top:

{@html
/// <reference types="vite-plugin-svelte-docgen" />
}

Usage

For the desired component you wish to import documentation data… simply append the ?docgen query to the module import path. For example:

Static import

{@html
import componentDocgen from "./path/to/Component.svelte?docgen";
//                                                     πŸ‘† Add this query parameter
}

Dynamic import

{@html
const componentDocgen = await import("./path/to/Component.svelte?docgen");
//                                                               πŸ‘† Add this query parameter
}

[!IMPORTANT] In case you’re seeing a TypeScript error like this one:

{@html
Cannot find module './path/to/Component.svelte?docgen' or its corresponding type declarations. [2307]
}

You have missed the TypeScript setup part.

[!TIP]

Yes, you can use it inside the Svelte component as well, just like so:

{@html
<script>
  import componentDocgen from "./path/to/Component.svelte?docgen";
  //                                                     πŸ‘† Don't forget to add it!
</script>
}