Skip to Content
The Public InterfaceSeptember 12, 2026

The Public Interface

January 12, 2023

Create a Svelte Component Library

How to create a npm package with SvelteKit to share your components between projects.

By Ross Robinosvelte / components / library

This post was updated on Mar 22, 2023 to account for the changes in svelte-package 2.0. This update simplified the process for setting up a component library. See instructions on migrating an existing project here. You can also now find more information on svelte-package in the documentation.

If you frequently have components that you share between projects and want to keep a single repository of them, you can create a package on npm. Here’s how to create a Svelte component library with SvelteKit.

Since this is a library project, it’s important to add in your relevant information to the package.json file so it will appear on npm when the package is published. The template sets much of this up for us, but we will need to edit a few fields.

You can read more on this in the svelte-package documentation.

An important note if you are planning on including CSS in your components–set the sideEffects field to false, if you want bundlers like Vite to be more aggressive with tree-shaking. If this field is not set, all of the CSS for every one of your exported components will be included when one component is imported. If your package does include modules with side effects that occur upon importing, you can specify them with an array of paths to the modules.

Find the latest information on this setting on this pull request I made.

The contents of the src/lib directory are what will be packaged upon running npm run package. This is where components can reside for the project as well as an index.ts file that exports the components for the package.

Create a component to export in your package, here’s my YouTube.svelte component as an example.

Import and export the component from src/lib/index.ts.

Do a quick test of your component on src/routes/+page.svelte by importing it to the page and running npm run dev -- --open.

Ensure that the component is working as expected, then you are ready to create a package.

Now we can package the library and publish it on npm for anyone to use. Repeat these steps each time you want to update your package.

If you are looking to automate some of these steps, check out the changesets project.

After verifying on the npm website that your package has been published, you can now use your package in a separate project.

You have now built a Svelte component library you can access from any of your other SvelteKit projects to share code between them.

Thanks for reading!…

Continue reading