svelte-prune
v0.16.1
Published
Ship only the Svelte library code your app renders.
Readme
svelte-prune
Ship only the Svelte library code your app renders.
A component library's Button handles every kind,
size and state any app might ask for,
and your bundle carries all of it.
svelte-prune reads how your app uses the library before the build,
then hands Svelte a copy of each component rewritten for the props it
actually receives: branches that can't run,
the components only they render, and the CSS only they use are cut from
the build.
Zero dependencies. Production builds in Vite, Rollup, Rolldown, webpack and Rspack, for Svelte 3, 4 and 5 (runes included), with source maps back to the original components.
Results
A realistic page per library, built with Vite with and without svelte-prune, gzipped:
| Library | Style | JS smaller by | CSS smaller by | | :---------------------------- | :------------------------- | :------------ | :------------- | | flowbite-svelte | Tailwind variants | 37.8% | 60.9% | | carbon-components-svelte | branches on props | 34.1% | 75.5% | | svelte-5-ui-lib | Tailwind variants | 22.9% | 71.7% | | @sveltestrap/sveltestrap | branches on props | 22.0% | 46.8% | | svelte-ux | Tailwind | 7.4% | 35.5% | | bits-ui | headless, state in classes | 2.2% | (no CSS) | | @skeletonlabs/skeleton-svelte | headless, state machines | 0% | 0% |
CSS is Tailwind's output for the Tailwind libraries (Tailwind) and the library's own stylesheet for Carbon and sveltestrap (Stylesheets). Libraries whose markup branches on their props gain the most, and so do those whose tailwind-variants tables hold every variant's classes. Headless libraries that keep their state in classes or hand their props to a state machine leave little to fold.
Every page renders and behaves identically in the browser, and 7,669 generated apps across these libraries render identically before and after (Correctness).
Install
bun i -d svelte-pruneWhat it removes
Each diff is the library component as svelte-prune rewrites it for the
app in its first comment
(Svelte 5 output; on Svelte 3 and 4 a live branch keeps its
{#if true} wrapper).
Branches that can't render, and the components only they render.
Icon is no longer bundled:
<!-- <Button kind="ghost">Save</Button> <Button kind="ghost" size="sm">Cancel</Button> -->
<script>
import Icon from "./Icon.svelte";
- export let kind = "primary";
export let size = "md";
</script>
-{#if kind === "danger"}
- <button class="btn danger {size}"><Icon name="warning" /><slot /></button>
-{:else if kind === "ghost"}
- <button class="btn ghost {size}"><slot /></button>
-{:else}
- <button class="btn primary {size}"><slot /></button>
-{/if}
+<button class="btn ghost {size}"><slot /></button>Props that never change become literals.
<!-- <Button size="sm">Save</Button> <Button size="sm">Cancel</Button> -->
<script>
- export let size = "md";
- export let disabled = false;
</script>
-<button class="btn btn-{size}" {disabled}><slot /></button>
+<button class="btn btn-{"sm"}" disabled={false}><slot /></button>Defaults no call site overrides, and the markup that only renders for other values:
<!-- <Field label="Name" /> -->
<script>
- export let label = "";
- export let helperText = "";
- export let invalid = false;
- export let id = "field";
</script>
-<label for={id}>{label}</label>
-<input {id} aria-invalid={invalid} />
-{#if helperText}<p class="helper">{helperText}</p>{/if}
+<label for={"field"}>{"Name"}</label>
+<input id={"field"} aria-invalid={false} />
+{#if false}<!---->{/if}Events nobody listens to.
A forwarded on:focus and a dispatch("change") go;
on:click has a listener and stays.
checked, which no call site passes,
becomes the component's own variable:
<!-- <Toggle on:click={log}>Dark mode</Toggle> -->
<script>
import { createEventDispatcher } from "svelte";
- export let checked = false;
+ let checked = false;
const dispatch = createEventDispatcher();
function toggle() {
checked = !checked;
- dispatch("change", checked);
}
</script>
-<button on:click on:focus on:click={toggle} aria-pressed={checked}><slot /></button>
+<button on:click on:click={toggle} aria-pressed={checked}><slot /></button>$$restProps spreads that carry nothing, onto components:
<!-- <Link href="/docs" icon="arrow">Docs</Link> -->
-<a {href}><slot />{#if icon}<Icon name={icon} {...$$restProps} />{/if}</a>
+<a href={"/docs"}><slot /><Icon name={"arrow"} /></a>Runes and snippets.
A snippet prop no call site passes is undefined:
<!-- <Card title="Usage">Body</Card> -->
<script>
let { title, variant = "outlined", header, children } = $props();
</script>
-<div class="card {variant}">
- {#if header}
- {@render header()}
- {:else if title}
- <h2>{title}</h2>
- {/if}
+<div class="card {"outlined"}">
+ <h2>{"Usage"}</h2>
{@render children?.()}
</div>Through your own components.
A wrapper's props come from its call sites,
so <Confirm tone="danger"> reaches the Button inside it:
<!-- src/Confirm.svelte, rendered only as <Confirm tone="danger">Delete</Confirm> -->
-<Button kind={tone}><slot /></Button>
+<Button kind={"danger"}><slot /></Button> <!-- the library's Button.svelte -->
-{#if kind === "danger"}
- <button class="danger"><slot /></button>
-{:else}
- <button class="primary"><slot /></button>
-{/if}
+<button class="danger"><slot /></button>tailwind-variants keys no live call selects,
with tailwind: true in the LibrarySpec.
Tailwind, scanning what svelte-prune writes,
leaves those classes out of your CSS too (Tailwind):
// <Badge color="green">Active</Badge> <Badge color="red">Failed</Badge>
export const badge = tv({
base: "rounded px-2",
variants: {
color: {
- gray: "bg-gray-100 text-gray-800",
red: "bg-red-100 text-red-800",
green: "bg-green-100 text-green-800",
},
- size: { sm: "text-xs", md: "text-sm", lg: "text-base" },
+ size: { md: "text-sm" },
},
defaultVariants: { color: "gray", size: "md" },
});Library stylesheet rules nothing renders,
with styles in the LibrarySpec (Stylesheets):
/* <Button>Save</Button>, whose class is btn-{kind} */
.btn { padding: 4px; }
.btn-primary { background: blue; }
-.btn-danger { background: red; }
-.btn-ghost { background: none; }
-.btn-danger:hover { background: darkred; }Svelte's hydration code, for an app that only mounts,
with hydration: false (Hydration).
Usage
Vite, Rollup and Rolldown
// vite.config.ts
import { svelte } from "@sveltejs/vite-plugin-svelte";
import { sveltePrune } from "svelte-prune/vite";
const library = {
name: "my-library", // the package your app imports
srcDir: "src", // where its .svelte files are, in the package
barrel: "index.js", // its entry, in srcDir
componentPackages: [], // packages whose exports are components (icon sets)
contextKeyPrefix: "my-library:", // what its context keys start with
label: "My Library", // names it in messages
tool: "svelte-prune", // starts every warning and error
};
export default {
plugins: [sveltePrune(library), svelte()],
};webpack and Rspack
// webpack.config.js
import { SveltePrunePlugin } from "svelte-prune/webpack";
export default {
plugins: [new SveltePrunePlugin(library)],
};It adds a loader that runs before svelte-loader on .svelte files.
Tailwind
Tailwind generates a utility for every class string it scans,
and a library's setup has it scan the
package (@source "../node_modules/my-library/dist").
For a library with tailwind: true in its
LibrarySpec, and with Tailwind installed,
every build writes what of the library can render to
node_modules/.svelte-prune/<name>: every file but the components that
can't render, as svelte-prune rewrote them
(components and tailwind-variants tables).
Scan that instead, with Tailwind v4's @source:
@source "../node_modules/.svelte-prune/my-library";or a Tailwind v3 content
glob: "./node_modules/.svelte-prune/my-library/**/*.{svelte,js}".
The dev server and development builds write the library as it is,
so their CSS has every class.
Stylesheets
A library that ships its own CSS
(Carbon's css/white.css, Bootstrap for sveltestrap) can name it
in styles:
const library = {
// …
styles: { stylesheets: ["my-library/css/*.css"] },
};Every production build then removes, from the CSS it emits,
the rules that need a class those stylesheets define
and that nothing can render.
A class stays when a live component can render it under the app's props
(a template with a part it can't evaluate keeps every class it could
build: btn-{size} keeps each btn- class),
when one of the library's script modules names it,
when a file in content names it, or when styles.keep
or the safelist option names it.
Classes the stylesheets don't define
(the app's own, Svelte's scoping classes, other packages') never remove
a rule.
A selector inside :not() or :has() doesn't need its classes;
an :is() list stays if any branch can match.
classTokens says how to read the library's class names.
Without it, every run of word characters and hyphens is a class,
which keeps more than a namespaced library needs:
a startsWith("x--") in its code would keep every x-- class.
A library whose classes share a prefix should pass its own:
classTokens: {
marker: "x--",
text: (text) => [...text.matchAll(/(?<![\w-])x--[\w-]+/g)].map(([t]) => `.${t}`),
script(code, into) {
for (const [t] of code.matchAll(/x--[\w-]+/g)) into.add(`.${t}`);
},
},Once those rules are gone, the custom properties (--x)
and @keyframes the stylesheets define go too when nothing reads them:
no var() or animation left in the emitted CSS,
and no file in content or source of the library naming them
(a script may read one, or build its name, as in `--tone-${t}`,
which keeps every --tone- property).
Only a class those tokens can read is ever removed.
Classes the app builds from data at runtime are the one thing it can't
see: list them, or a RegExp for their selectors, in safelist.
Hydration
An app that renders in the browser only
(mount(), no server-rendered HTML to pick up) can pass
hydration: false to the Vite plugin:
sveltePrune(library, { hydration: false });Svelte 5's client runtime guards its hydration code with a variable a
bundler can't prove is always false, so every app ships it.
With hydration: false it becomes a constant,
and hydrate() throws before it runs, so the minifier drops both.
On the example pages, on top of svelte-prune, gzipped:
| Library | JS smaller by | | :---------------------------- | :------------ | | @sveltestrap/sveltestrap | 4.7% | | bits-ui | 3.5% | | @skeletonlabs/skeleton-svelte | 3.2% | | svelte-5-ui-lib | 2.8% | | flowbite-svelte | 2.7% | | svelte-ux | 2.1% | | carbon-components-svelte | 1.8% |
Each page behaves identically in Chromium both ways.
A build whose output can still reach hydrate() fails:
SvelteKit with SSR, hydrate imported from svelte,
or a class component from
svelte/legacy (new App({ hydrate: true })).
Svelte 3 and 4 bundle hydration code only for components compiled with
hydratable, so they ignore it, with a warning.
So does the webpack plugin: webpack bundles Svelte's custom element
class, and through it hydrate(), whatever the app calls,
so no build could show the app never hydrates.
API reference
svelte-prune has no CLI: it runs inside your bundler
(svelte-prune/vite, svelte-prune/webpack),
or from your own script with specializeFiles (svelte-prune).
Each entry ships its own types:
import {
type LibrarySpec,
type SveltePruneOptions,
specializeFiles,
} from "svelte-prune";
import type { Failure, SpecializedComponents } from "svelte-prune";
import { sveltePrune } from "svelte-prune/vite";
import { SveltePrunePlugin, type WebpackCompiler } from "svelte-prune/webpack";sveltePrune(library, options?, names?)
import { sveltePrune } from "svelte-prune/vite";
function sveltePrune(
library: LibrarySpec,
options?: SveltePruneOptions,
names?: PluginNames & { id: string },
): Plugin;A Vite, Rollup and Rolldown plugin. Put it before the Svelte plugin.
- Rewrites on
vite buildonly (--watchincluded), never on the dev server, which runs only to write the library as it is for Tailwind (tailwind: true). Rollup and Rolldown have no dev server: add it only to production configs there. buildStartreadscontent, resolving aliased.svelteimports ($lib/Card.svelte) with the bundler. A watch rebuild where nothing incontentchanged reuses the last analysis.loadserves the rewritten components, with source maps;transformandbuildEndcheck the module graph and fail the build when a module the analysis didn't read imports the library (see Errors).
new SveltePrunePlugin(library, options?, names?)
import { SveltePrunePlugin } from "svelte-prune/webpack";
class SveltePrunePlugin {
constructor(
library: LibrarySpec,
options?: SveltePruneOptions,
names?: Partial<PluginNames & { loader: string }>,
);
apply(compiler: WebpackCompiler): void;
}A webpack 5 and Rspack plugin.
It rewrites nothing unless mode is "production"
(an unset mode counts); other modes only write the library as it is
for Tailwind (tailwind: true).
It adds a pre-loader on .svelte files and the library's script
modules, so svelte-loader compiles the rewritten source wherever the
plugin sits in plugins, analyzes content on beforeRun
and watchRun, and checks the module graph on finishModules.
LibrarySpec
Describes the library to rewrite.
Every field but classTokens, styles and tailwind is required.
| Field | Type | |
| :------------------ | :------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name | string | The package apps import: "my-library". |
| srcDir | string | The directory of its .svelte files in the package: "src". |
| barrel | string | Its entry, relative to srcDir: "index.js". |
| componentPackages | readonly string[] | Packages whose exports are components (an icon set), so passing one as a prop passes an object. |
| contextKeyPrefix | string | What its context keys start with ("my-library:"): an app module that holds such a string may set or read its contexts. |
| label | string | Names the library in messages: "My Library". |
| tool | string | Starts every warning and error: "svelte-prune". |
| classTokens | { marker, text, script } | Optional. How to read the library's class names: text returns the classes (.x--a) in a string that contains marker, script adds those a whole script module names. Without it, a library with styles reads every run of word characters and hyphens. See Stylesheets. |
| styles | { stylesheets, keep? } | Optional. stylesheets: the library's CSS, as "<package>/<path>" with * matching within a path segment. keep: classes always kept. With it, production builds prune those stylesheets' rules from the CSS they emit (see Stylesheets). |
| tailwind | boolean | Optional, false by default. true for a library whose classes are Tailwind's: its tailwind-variants tables are rewritten, and with Tailwind installed, builds write what of it can render for Tailwind to scan, the dev server's and non-production webpack builds included. Without it, the analysis never loads that code, and the plugins skip those builds entirely. |
SveltePruneOptions
| Option | Default | |
| :--------- | :--------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| content | ["src/**/*.{svelte,svx,md,mdx,astro,js,jsx,ts,tsx,mjs,mts,cjs,cts}"] | Every file that renders the library's components, relative to the project root. They're analyzed before the build; a module outside them that imports one fails the build. .svelte files are read for the props they pass; a component imported from a script, Markdown, MDX or Astro file keeps every value. node_modules is skipped unless a pattern names it. |
| unwrap | true on Svelte 5 | Replace an {#if} whose only live branch is known with that branch, instead of {#if true}. Svelte 3 and 4 render whitespace differently without the block. |
| silent | false | Skip the per-build summary (rewrote N My Library components for this app (M edits)). |
| report | false | Print what each build rewrote: edits per component, the children it no longer renders, the components no longer bundled, and the values each call site passes (or why it keeps every value). Independent of silent. |
| safelist | [] | Selectors of the library's stylesheets to keep whatever renders, for classes the app builds from data at runtime: a class ("x--tag--red", with or without its .) keeps every selector it's in, a RegExp every selector it matches (/^\.x--tag--/). Only with styles. |
| hydration | true | false for an app that only mounts, never hydrating server-rendered HTML: Svelte 5's client runtime loses its hydration code, and a build whose output can still call hydrate() fails. Vite, Rollup and Rolldown only. See Hydration. |
names
For a package that wraps svelte-prune and reports under its own name.
sveltePrune() replaces its defaults whole, so pass plugin,
failure and id; SveltePrunePlugin takes any of its fields.
| Field | Default | |
| :----------------- | :------------------------------------ | :----------------------------------------------------------------------------------------------------------------------- |
| plugin | "svelte-prune" | Names the plugin in errors, and webpack's hooks and logger. |
| failure.feature | "svelte-prune" | Names what a failed analysis turns off, in its warning and the report heading (after tool, unless they're the same). |
| failure.fallback | "components were bundled unchanged" | What happens instead, in that warning. |
| id | "svelte-prune" | sveltePrune() only: the plugin's name in the bundler. |
| loader | the bundled loader | webpack only: the path of the loader to add. |
specializeFiles(input)
import { specializeFiles } from "svelte-prune";
function specializeFiles(input: {
library: LibrarySpec;
projectRoot: string;
files: Array<{ file: string; code: string }>;
failure: Failure;
options?: SpecializeOptions;
resolvedImports?: ReadonlyMap<string, string>;
safelist?: ReadonlyArray<string | RegExp>;
}): Promise<SpecializedComponents | { warning: string }>;The analysis and rewrite the plugins run, for a set of files and without a bundler. Pass every file that renders the library: a component a missing file renders is rewritten without its call sites.
| Input | |
| :------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| library | The LibrarySpec. |
| projectRoot | Where the library is resolved from (Yarn Plug'n'Play included), and what the report's paths are relative to. |
| files | Absolute paths and their source. |
| failure | { feature, fallback } for the warning if the analysis throws. |
| options.unwrap | Defaultfalse. As in SveltePruneOptions; pass true on Svelte 5. |
| options.dropUnused | Defaulttrue. Remove top-level declarations nothing reads after the rewrite. |
| options.emptyBlock | Default{#if false}<!---->{/if}. What replaces an {#if} that renders nothing between whitespace. |
| options.editFilter | (index, { start, end }) => boolean. Debugging: apply only the top-level edits it accepts. |
| resolvedImports | Non-relative .svelte imports you resolved yourself ($lib/Card.svelte), keyed `${importer}\0${specifier}`, to the absolute path of a file in files. |
| safelist | As in SveltePruneOptions. |
It never throws: if the analysis fails,
it resolves to { warning } and nothing is rewritten.
Otherwise to SpecializedComponents:
| Field | Type | |
| :------------ | :------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| sources | Map<string, { code: string; map: SourceMap }> | Rewritten components and script modules by the real path of their source, each with a v3 source map. Serve these instead of the files on disk. |
| edits | number | Edits made to components, across sources. |
| apps | number | How many of sources are the app's own components. |
| renderable | ReadonlySet<string> | The library components that can render, by path in srcDir. |
| tables | { modules, pruned, emptied, keys, compounds } | The tailwind-variants tables rewritten: how many of sources are their modules, tables pruned and emptied, and variant keys and compound variants removed. |
| closed | Set<string> | App components whose props came from their call sites in files. Nothing outside files may render them; the plugins check it. |
| report | () => string[] | The lines report: true prints. |
| readImport | (importer, id) => boolean | Whether the analysis read file importer's import of library module id (both real paths). false means an import it can't see, such as one through a bundler alias. |
| pruneStyles | (css) => { css, rules, selectors, declarations } | With styles: removes from css the rules that need a class the library's stylesheets define and nothing can render, then the custom properties and @keyframes they define that nothing reads, and counts what it removed. |
const result = await specializeFiles({
library,
projectRoot: process.cwd(),
files: [{ file: "/app/src/App.svelte", code }],
failure: {
feature: "svelte-prune",
fallback: "components were bundled unchanged",
},
options: { unwrap: true },
});
if ("warning" in result) console.warn(result.warning);
else
for (const [file, { code, map }] of result.sources)
console.log(file, code, map);Warnings and errors
Every message starts with `${tool}:`.
- Warning (the build continues, nothing rewritten):
could not analyze this build (…), when the analysis throws, for example because the library isn't installed. - Warnings for
hydration: false(the build continues with Svelte's hydration code):ignored \hydration: false`, on Svelte 3 and 4 and under webpack and Rspack;left Svelte's hydration code in this build`, when the installed Svelte's runtime isn't one it can rewrite. - Errors (the build fails), when components were rewritten without a
call site:
- a file outside
contentimports the library: add it tocontent; - an analyzed file imports the library through an alias the analysis
can't read (
import { Button } from "@lib"): import it from the package name; - a virtual module (no file on disk) imports the library:
import it from a file in
content; - a module outside
contentrenders an app component whose props were read from its call sites: add it tocontent; - a module outside the library imports one of its script modules whose tailwind-variants tables were rewritten (through an alias, for example): import them from the package name.
- a file outside
- Error with
hydration: false, when the output can still callhydrate()(SvelteKit with SSR,hydratefromsvelte, a class component fromsvelte/legacy): mount the app withmount(), or remove the option.
What it reads
Each diff is rewritten for the call site in its first comment; the values come from what that call site passes.
Names declared in markup.
A {@const}, an {#each} item, and destructuring in either are read
where they're in scope, and so is a snippet's parameter,
as what every {@render} of it passes:
<!-- <List size="md" {items} /> -->
{#snippet row(s, label)}
- {#if s === "sm"}<small>{label}</small>{:else}<b>{label}</b>{/if}
+ <b>{label}</b>
{/snippet}
{#each items as { label, tags: [first] = [] }}
- {@const compact = size === "sm"}
- {#if compact}<small>{first}</small>{/if}{@render row(size, label)}
+ {@const compact = false}
+ {@render row("md", label)}
{/each}A snippet handed to a component, or used as a component's content, keeps its parameters unknown: the component may call it with anything.
Pure built-ins.
Array.isArray, Math's rounding and min/max functions,
and includes, some and every on arrays
(some and every with a callback written inline that only reads) are
evaluated, and a &&, || or ??
whose left side decides it folds without its right side:
<!-- <Header title="Hi" placement="left" /> -->
-{#if Array.isArray(title)}{#each title as t}<p>{t}</p>{/each}{:else}<p>{title}</p>{/if}
-{#if ["top", "bottom"].includes(placement)}<div class="vertical">…</div>{/if}
-{#if Array.isArray(data) && data.length > 0}<datalist>…</datalist>{/if}
+<p>{"Hi"}</p>
+{#if false}<!---->{/if}
+{#if false}<!---->{/if}Array or Math declared in the component isn't the built-in,
and an object's own includes may do anything.
Stores handed down in a context.
A writable a component sets only from its props, in $:,
and hands down only in setContext,
holds what those props can be in every component that reads it:
<!-- Tabs.svelte -->
<script>
export let iconOnly = false;
const iconOnlyStore = writable(iconOnly);
$: iconOnlyStore.set(iconOnly);
setContext("tabs", { iconOnly: iconOnlyStore });
</script> <!-- Tab.svelte, in <Tabs><Tab label="One" /></Tabs> -->
<script>
const { iconOnly } = getContext("tabs");
</script>
-{#if $iconOnly}<Tooltip text={label}><slot /></Tooltip>{:else}<span>{label}</span>{/if}
+<span>{label}</span>Tooltip is no longer bundled.
A store a reader may write, or that a provider above may receive,
keeps every value.
Only what the app uses. A component your app imports but never names again (not in markup, scripts, comments or strings) adds no call site, so it's specialized only for where the library itself renders it:
<script>
import { TextField, Field } from "my-library"; // Field: unused
</script>
<TextField label="Name" />TextField renders <Field placement="inset">,
so Field keeps only its inset branch.
How it stays safe
Unknown means open. A component keeps every value of a prop the analysis can't read, and is rendered with any props wherever it can't see the call site:
A prop passed as an expression it can't evaluate, spread from an object it can't read, or bound with
bind:keeps every value.A component used as a value (
this={Button}, passed as a prop), imported dynamically or through an alias, or rendered from a file outsidecontentkeeps every variant. The plugins check the bundler's module graph after the build and fail it when a module the analysis didn't read imports the library.A component whose props something other than a call site can set keeps every value: a custom element, or one bound with
bind:thiswhose instance the app uses for more than calling what it exports ($set, an accessor,$on, handing it on).A prop nothing reads anymore stays declared where removing it would show: its default has effects (
uniqueId()), something writes it, or a call site passes it to a component that reads$$restPropsor$$props, where it would land.A prop becomes a plain
letonly when no call site passes or binds it.A bare
on:clickstays wherever a call site may listen to it: one withon:click, one whose own forwardedon:clickhas a listener, or one the analysis can't read. So does adispatch("click", …), and one goes only where its result is unused (truein the browser,undefinedon the server), keeping whatever its arguments run.$$restPropsis spread away only when no call site passes a key it would hold, and only onto components and into objects: on an element, a spread decides how Svelte renders its attributes.Content counts: snippets are props, and content outside them is
childrenon Svelte 5 and a slot on Svelte 3 and 4.An export of the library it can't tell apart from a component (a function that may return one) keeps every component.
A tailwind-variants table keeps every key when something other than a live component's call can read it: the app imports it, another table extends it, a script module reads it, a namespace or
import()reaches it, or a component hands on what a call with slots returns. A variant whose value at some call the analysis can't evaluate (a spread, a function's parameter) keeps every key. A table nothing calls is emptied only when nothing else can read it, and a script module that mounts a component keeps every table whole.A stylesheet rule stays unless it needs a class the library's stylesheets define, its
classTokenscan read, and nothing can render: no live component under the app's props, no script module of the library, no file incontent, nothing inkeeporsafelist. The examples check that no selector whose classes all appear on the rendered page goes missing.With
hydration: false, Svelte's runtime is rewritten only when both of its modules are exactly as expected, and the build fails ifhydrate()survives bundling: an output that can reach it is one that may hydrate.
The app's own components are rewritten too,
when every file that renders them is in content:
a wrapper's props come from its call sites,
so <Card tone="danger"> reaches the Button inside it.
Correctness
On real libraries, each component with every prop value it compares against plus random mixes of them, SSR-rendered with the original and the rewritten library:
| Library | Components | Apps rendering identically | Apps rendering differently | | :---------------------------- | :--------- | :------------------------- | :------------------------- | | carbon-components-svelte | 262 | 2,330 | 0 | | @sveltestrap/sveltestrap | 87 | 645 | 0 | | svelte-ux | 101 | 999 | 0 | | flowbite-svelte | 181 | 1,591 | 0 | | svelte-5-ui-lib | 135 | 918 | 0 | | bits-ui | 159 | 859 | 0 | | @skeletonlabs/skeleton-svelte | 131 | 327 | 0 |
The example pages behind Results also compare each page's rendered HTML and its behavior in a browser, and fail when a selector whose classes all appear on the page goes missing from the CSS.
Limitations
- Production builds only. The analysis runs for the whole app before the build, so dev serving and HMR are left alone.
- tailwind-variants tables only in the library's
.jsmodules, made withtvimported fromtailwind-variants. Tables defined in components, or withcreateTV, keep every class. - Every importer must be in
content. A module outside it that imports the library fails the build rather than ship components rewritten without its call sites. - Stylesheets can't see classes built from data.
A class the app or a package outside the library adds at runtime,
from a value no file names, must be in
safelist. - Values it can't evaluate stay open.
Props read from a whole
$props()object, or state held in classes (.svelte.js), keep every value.
