Skip to content

@ogygia/tsdown-plugin-svelte

How it works

The four steps of a build, from preprocessing each component to copying only the component declarations next to the shipped files, and the scratch files it makes and removes.

On this page

The plugin does its work in two build hooks, buildStart and writeBundle, so tsdown (or rolldown) stays in charge of your .ts files and their declarations. Given this component:

the build ships this, beside util.js:

<script lang="ts">
  import { greet } from './util.ts';
  type Row = { id: number; label: string };
  let { name, rows }: { name: string; rows: Row[] } = $props();
</script>

<button>{greet(name as string)}</button>
{#each rows as row (row.id)}
  {#snippet cell(r: Row)}<b>{r.label}</b>{/snippet}
  {@render cell(row)}
  <i>{row!.label}</i>
{/each}
<script>import { greet } from "./util.js";
let { name, rows } = $props();
</script>

<button>{greet(name)}</button>
{#each rows as row (row.id)}
  {#snippet cell(r)}<b>{r.label}</b>{/snippet}
  {@render cell(row)}
  <i>{row.label}</i>
{/each}

Build steps

  1. Preprocess. At the start of the build, every .svelte file under src is run through your preprocessors, which turn its <script lang="ts"> into JavaScript.
  2. Strip the markup. Svelte’s parser reads the file once more, as TypeScript, and every type-only part of the template is cut out (Markup stripping). lang="ts" is removed from each script. A relative ./x.ts import, static, dynamic or in a JSDoc import() type, becomes ./x.js, the built module beside it, the way tsdown rewrites your .ts sources.
  3. Emit. The result is emitted as a build asset at the same path under out, and each .css file under src is emitted as it is. Emitted assets, unlike files written to disk, survive tsdown’s clean.
  4. Types. After the bundle is written, svelte2tsx generates declarations for everything under src into a scratch folder, and only the *.svelte.d.ts files are copied next to the components, with the same ./x.ts to ./x.js rewrite. Declarations svelte2tsx makes for your .ts files are thrown away: those are tsdown’s.

What ships is a .svelte file with plain JavaScript in its script, no TypeScript in its template, and its styles as written. Your users’ Svelte compiles it like any component in their own app.

Scratch files

Step 4 writes two things in root while it runs, and removes both when it’s done, whether or not it succeeded: the folder .svelte-dts/, and .svelte-dts.tsconfig.json, your tsconfig extended with isolatedDeclarations off. A build that’s killed mid-way can leave them behind, so add both to .gitignore:

.svelte-dts/
.svelte-dts.tsconfig.json