@ogygia/tsdown-plugin-svelte
Markup stripping
strip_markup_ts removes TypeScript from a Svelte component's template, and js_specifiers points its relative .ts imports at .js, for tools that ship Svelte source another way. Run them on the output of preprocess(), when the script is JavaScript but the template still has types.
On this page
Svelte’s preprocess() turns a component’s <script lang="ts"> into JavaScript, but it never touches the template, so {item as Row} survives it. strip_markup_ts is the step of the plugin’s build that removes it, exported for tools that ship Svelte source another way. js_specifiers is the step after it. Run both on the output of preprocess():
import { readFileSync, writeFileSync } from 'node:fs';
import { preprocess } from 'svelte/compiler';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
import {
js_specifiers,
strip_markup_ts
} from '@ogygia/tsdown-plugin-svelte';
const filename = 'src/Button.svelte';
const source = readFileSync(filename, 'utf8');
const { code } = await preprocess(
source,
vitePreprocess({ script: true }),
{ filename }
);
writeFileSync(
'dist/Button.svelte',
js_specifiers(strip_markup_ts(code, filename))
);strip_markup_ts
strip_markup_ts(source, filename?) parses the file with Svelte’s own parser, as TypeScript, and cuts out every type-only part of the template:
| Written | Shipped |
|---|---|
{name as string} | {name} |
{config satisfies Config} | {config} |
{user!.name} | {user.name} |
{<string>value} | {value} |
{#snippet row(item: Row)} | {#snippet row(item)} |
{((x: number): number => x + 1)(n)} | {((x) => x + 1)(n)} |
{pick<Row>(rows)} | {pick(rows)} |
It also removes lang="ts" from the instance and the module script, with the space before it, and keeps their other attributes. Everything else stays byte for byte as it was. Strings and comments that only look like types are left alone, because nothing is matched by pattern. filename is passed to the parser, for its error messages, and a template that doesn’t parse throws Svelte’s own error.
It doesn’t touch the script’s content: that’s the preprocessor’s job. It knows the file is TypeScript by the lang="ts" (or lang='ts') that preprocess() leaves on the script. A file without it is returned unchanged.
js_specifiers
js_specifiers(source) rewrites each relative import that ends in .ts to end in .js: static imports, import() calls and JSDoc import() types, starting ./ or ../. A shipped component sits beside the built modules, so ./util.ts has to become ./util.js. Package imports and other extensions stay as they are. The plugin runs it on each component and each .svelte.d.ts.
import { js_specifiers } from '@ogygia/tsdown-plugin-svelte';
js_specifiers(`import { greet } from './util.ts';`);
// import { greet } from './util.js';