# A component library in Svelte

- Published: 2026-12-03
- Tags: Why Svelte, Svelte
- URL: https://devtrillo.com/writing/why-svelte-20-a-component-library-in-svelte/

> Part 20 of a series on Svelte in 2026. [Part 19](/writing/why-svelte-19-svelte-vs-react-one-component-two-ways/) wrote one component in Svelte and in React. This part takes a Svelte component out of its app and ships it to another one.

A component library starts the day a second app wants your Button. You can copy the file across, and that works until one app fixes the focus ring and the other doesn't. A package gives the fix one home, and it gives you a new job: making sure the thing you publish works somewhere you didn't write.

That second part is where I got caught. I scaffolded a library with the official template, wrote one Button, ran `publint`, which printed "All good!", and packed it. The library's own demo page built. Then I installed the tarball in a fresh SvelteKit app and the build failed on the first import.

So this post is about the boundary. A Svelte library is mostly ordinary Svelte; what changes is that every file now gets read by someone else's compiler, through someone else's resolver, and the only way to see what they see is to stand where they stand.

The lab ran `sv` 1.1.1 (the CLI's library template), Svelte 5.57.3, SvelteKit 3.1.0, `@sveltejs/package` 2.5.8 and then 3.0.1, Vite 8.3.5, `publint` 0.3.25 and `svelte-check` 4.7.7 on Node 24.

## One component, one barrel

`npx sv create lib --template library` gives you a SvelteKit project where `src/lib` is the package and `src/routes` is a sandbox for demos or docs.[^package] Here's the Button I put in it:

```svelte title="src/lib/Button.svelte"
<script lang="ts">
  import type { Snippet } from "svelte";
  import type { HTMLButtonAttributes } from "svelte/elements";
  import Spinner from "#lib/Spinner.svelte";

  type Props = HTMLButtonAttributes & {
    children: Snippet;
    tone?: "normal" | "danger";
    loading?: boolean;
  };

  let {
    children,
    tone = "normal",
    type = "button",
    loading = false,
    ...rest
  }: Props = $props();
</script>

<button {...rest} {type} data-tone={tone} aria-busy={loading}>
  {#if loading}<Spinner />{/if}
  {@render children()}
</button>

<style>
  button {
    padding: 0.5rem 1rem;
    border: 0;
    border-radius: var(--ui-radius, 0.375rem);
    color: var(--ui-button-text, white);
    background: var(--ui-button-bg, #222);
    font: inherit;
  }
  button[data-tone="danger"] {
    background: var(--ui-danger, #a31515);
  }
</style>
```

Most of it is [part 6](/writing/why-svelte-6-props-are-getters/) and [part 7](/writing/why-svelte-7-children-is-a-function/): typed props, a rest spread so `onclick`, `disabled`, `class` and `aria-*` pass straight through, and `children` as a snippet. Two choices are about the library rather than the component. `type` defaults to `"button"`, because a button inside a form submits it unless told otherwise, and nobody using your library expects that from a component called Button. And the colours come from CSS custom properties with fallbacks, which is the theming API; more on why below.

`Spinner` is a second component, a bordered `<span aria-hidden="true">`, imported through `#lib`. SvelteKit 3 replaced the `$lib` alias with that Node subpath import, and the template's `package.json` maps it: `"#lib/*": "./src/lib/*"`.[^kit3] Components importing siblings through the alias is about as ordinary as library code gets.

The barrel is the public API, and Spinner isn't in it:

```ts title="src/lib/index.ts"
export { default as Button } from "./Button.svelte";
```

## What svelte-package hands over

`npm run prepack` runs `svelte-package`, then `publint`. The output in `dist/` was seven files: each component plus its `.d.ts`, `index.js` and `index.d.ts`, and a theme stylesheet I'll come back to.

The `.svelte` file is still a `.svelte` file. That surprised me the first time I saw it, coming from React, where a library ships compiled JavaScript. A Svelte library ships source, preprocessed, and the consumer's Svelte compiles it alongside their own components. That's why the package's `exports` uses a `svelte` condition, and why `svelte` is a peer dependency: the library has to be compiled by the same Svelte the app runs. Here `dist/Button.svelte` even kept `lang="ts"`, since the template doesn't add a TypeScript preprocessor and Svelte 5 strips types itself.

The declaration file came out clean:

```ts title="dist/Button.svelte.d.ts"
type Props = HTMLButtonAttributes & {
  children: Snippet;
  tone?: "normal" | "danger";
  loading?: boolean;
};
declare const Button: import("svelte").Component<Props, {}, "">;
```

And then the line that broke everything, in `dist/Button.svelte`:

```svelte
import Spinner from "#lib/Spinner.svelte";
```

Unchanged. `publint` packed the tarball, linted it and said "All good!"

## The import that only worked at home

I packed the library with `npm pack`, ran `npm install ../lib/lib-0.0.1.tgz` in a fresh app from `sv create --template minimal`, and imported `Button`. `vite build` stopped with:

```text
Rolldown failed to resolve import "#lib/Spinner.svelte" from
".../app/node_modules/lib/dist/Button.svelte".
```

A `#` import resolves against the `imports` field of the nearest `package.json`, which for that file is the library's own. That field points at `./src/lib/*`, and `files` only ships `dist`, so the target isn't in the tarball at all. The library's demo route built fine, of course, because in the library repo `src/lib` exists.

The docs say `svelte-package` "rewrites `#`-prefixed imports from your package.json `imports` field to relative paths when packaging."[^package] It does, from `@sveltejs/package` 3.0.0 ("transform import aliases into relative imports").[^changelog] The `sv` 1.1.1 library template I scaffolded asks for `^2.5.8`, and a caret range never crosses a major, so a fresh project installs 2.5.8 and gets the docs' advice without the docs' behaviour. After `npm install -D @sveltejs/package@3.0.1` the packaged line read `import Spinner from './Spinner.svelte'` and the consumer built.

By the time you read this, the template may well ask for 3. The lesson outlives the bug, though. Four checks looked at this package and passed: the demo route's build, `svelte-check` in the library (0 errors), `svelte-package` itself, and `publint`. All four ran from inside the library, where the broken path happened to exist.

**Quiz:** Your library's demo route renders every component correctly. What does that tell you about the published package?

- The package works, since the demo imports the same components
- Very little. It never resolves dist/ through the package's exports and files.
- That the types are right, because svelte-check passed

**Answer:** Very little. It never resolves dist/ through the package's exports and files. — Only an app that installs the packed tarball resolves the package the way a user will. That's the check that caught the #lib import.

- Not "The package works, since the demo imports the same components": The demo imports src/lib, not dist/. It resolves aliases against your repo and never sees what files ships.
- Not "That the types are right, because svelte-check passed": svelte-check in the library checks src/lib. The consumer's svelte-check is the one that reads the generated .d.ts files.

## Styles cross the boundary on your terms

With the import fixed, the consumer page used the Button twice, the second time with a class the page styled:

```svelte title="app/src/routes/+page.svelte"
<Button onclick={() => (count += 1)}>Count: {count}</Button>
<Button tone="danger" class="special">Delete</Button>

<style>
  .special {
    outline: 4px solid red;
  }
</style>
```

The build passed, the rendered HTML had `class="special svelte-1umyizs"` on the second button, and the Svelte plugin warned: `Unused CSS selector ".special"`. [Part 11](/writing/why-svelte-11-scoped-styles-css-that-stays-put/) covered why. The page's styles are scoped to elements the page renders, and the `<button>` belongs to the library. The class reaches the element, because the Button passes it through, but the page's rule doesn't reach the class. A consumer can get around it with `:global(.special)`, and some will, but it's not something the library can promise to keep working, because the internal markup isn't the API.

The custom properties are. `--ui-button-bg`, `--ui-radius` and friends cross scoping by design, because they inherit through the DOM. That makes them the right surface for theming, and it means renaming one is a breaking change, same as renaming a prop.

A shared theme file was the next thing to go wrong. I'd put defaults in `src/lib/styles/theme.css`, and it shipped as `dist/styles/theme.css`. In the app, `import "lib/styles/theme.css"` failed the build:

```text
"./styles/theme.css" is not exported under the conditions
["module", "node", "production", "svelte", "import"] from package
```

The file was in the tarball. The `exports` map just didn't list it, and once a package has `exports`, nothing outside it can be imported. One more entry fixed it, and gave the stylesheet a path I'd be willing to keep:

```json title="package.json (exports)"
{
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "svelte": "./dist/index.js"
    },
    "./theme.css": "./dist/styles/theme.css"
  }
}
```

After that, `import "lib/theme.css"` built and the theme's `--ui-button-bg:#0a50c8` landed in the app's CSS. Keep the template's `"sideEffects": ["**/*.css"]` while you're in there. Vite doesn't need it; the docs keep it so the stylesheet survives webpack's tree-shaking.[^package]

## The types make it across

With `tone="loud"` on the second Button, the consumer's `svelte-check` reported:

```text
Type '"loud"' is not assignable to type '"normal" | "danger" | undefined'.
```

That's the generated `.d.ts` doing its job in an app that never saw the library's source. It's the part of the pipeline I'd worry about least: write typed props, and `svelte-package` turns them into declarations without being asked.[^package]

**Quiz:** A user wants your Button's corners square. Which of these should your library treat as public API?

- A :global(button) rule in their stylesheet
- Setting --ui-radius: 0 on a parent element
- Passing class and styling that class in their component

**Answer:** Setting --ui-radius: 0 on a parent element — Custom properties inherit through scoping, and you documented this one. Renaming it is a breaking change you'll know you're making.

- Not "A :global(button) rule in their stylesheet": It works today, but it depends on your internal markup. Wrap the button in a span next release and it breaks.
- Not "Passing class and styling that class in their component": The class reaches the element, but their scoped rule doesn't. Svelte will warn that the selector is unused.

## Build it, or own it

You don't have to write every primitive yourself, and for anything harder than a button you shouldn't. Bits UI is a headless library: its components ship almost entirely unstyled, with the behaviour, keyboard handling and ARIA wiring done.[^bits] A design-system package can wrap its Dialog in your styles and a smaller prop list, and if you do, the accessible name, focus trap and Escape-to-close are now yours to keep working. Bits UI goes in your `dependencies` or `peerDependencies`, and either way your consumers install it.

shadcn-svelte goes the other way. Its docs open with "This is not a component library. It is how you build your component library."[^shadcn] The CLI copies component source, built on Bits UI and Tailwind, into your project, and from then on you edit it like your own code. That's the right model for one app that wants to change everything. For three apps that need the same fix on the same day, it's three copies, and a package is still the thing that keeps them in step.

Which one fits depends on how many consumers you have. With one app, keep components in `src/lib` and skip the package. When a second app needs them, the [design-system series](/writing/design-system-1-build-your-own-design-system/) covers the decisions about what goes in; this post covers what makes it out.

## What I'd do on day one

Make a consumer app the first thing you add, before the second component. Install the packed tarball in it, not a workspace link, run its `build` and `check` in CI, and write the tests you'd otherwise write in the demo route against that app's pages. It caught all three problems I hit, and nothing inside the library caught any of them.

Then pin `@sveltejs/package` to 3 or later if you use `#lib`, list every importable path in `exports`, and keep `svelte` a peer dependency. React's library story asks you to compile and bundle; Svelte's asks you to ship source and let the app compile it, which is less work for you, as long as you check it from the app's side of the fence.

Next: setting up Svelte with Tailwind v4.

[^package]: SvelteKit docs, [Packaging](https://svelte.dev/docs/kit/packaging): the `dist` output, export conditions, `sideEffects`, TypeScript declarations, and "Best practices" for subpath imports.

[^kit3]: SvelteKit docs, [Migrating to SvelteKit 3](https://svelte.dev/docs/kit/migrating-to-sveltekit-3), covered in [part 16](/writing/why-svelte-16-migrating-to-sveltekit-3-with-sv-migrate/).

[^changelog]: [`@sveltejs/package` changelog](https://github.com/sveltejs/kit/blob/main/packages/package/CHANGELOG.md), 3.0.0 (released 2026-10-01), "feat: transform import aliases into relative imports in files" (#16360).

[^bits]: [Bits UI](https://www.bits-ui.com/docs/introduction), "Bring Your Own Styles".

[^shadcn]: [shadcn-svelte, Introduction](https://www.shadcn-svelte.com/docs).

- **Part 21 — Svelte + Tailwind v4 setup**: Wiring Tailwind v4 into a Svelte project
