DEV Community

Cover image for Use SvelteKit to create npm packages
Domenik Reitzner
Domenik Reitzner

Posted on

Use SvelteKit to create npm packages

I have been using svelte for about 3 years and have had a lot of fun with it. The simplicity of using it, or the ability to jump into the REPL and trying out a crazy idea are just some of the great things that make it such a pleasure to use.

The next big thing

Almost a year ago things were about to get even better. SvelteKit, the application framework for Svelte apps was announced and entered public beta. SvelteKit is to Svelte what Next is to React or Nuxt is to Vue.

One of the hidden features included with this new tool-belt for building Svelte Apps is the command svelte-kit package.

This command will auto-generate a package from your src/$lib folder (this is a special folder for your shared code/components in SvelteKit) that you can publish directly to npm.

But I am getting ahead of myself. Let'S look at the steps in more detail 😉

Setup your project

To get started run npm init svelte@next my-app.

I would recommend to select the following:

  • skeleton project

  • typescript

  • prettier

  • eslint

as they should make your live easier especially when working in teams.

There is one more package you need to add by running npm i -D svelte2tsxin your my-app folder.

Now you should be set to start with your first changes.

Good first adaptions

I have developed a mental list of things that I want to do right in the beginning, as I tend to forget them when I jump into the thick of things.

The first thing I take care of is to make some adaptions to the package.json. Specifically I make sure that the package name is correct (had some upsis there). It also makes sense to add a namespace (I created a svackages organisation for all my svelte packages).

Other good things to add are the fields repository, bugs and license.

To finish off this part, I do a rudimentary documentation in the of how my code should work. This step is important as it will be the info shown on npm as soon as you publish. Ideally I will already add REPL url, where my future package will be easy to try out.

Add your code

The next part should be the easiest. Add all the code that you want to publish in src/$lib. To make it easier on yourself, you can use the src/routes folder to test out your package. This is also a nice way of documenting your package and possibly even publishing it as a standalone site.

Publish it

The last few steps to get your library published are actually pretty easy.

  • run npm run package to generate your package

  • Make sure that you are logged into npm (npm login)

  • the last thing to do is to run npm publish ./package (hopefully you have two factor authentication and need to put in your code as well)

Now you have successfully published your (first) package with SvelteKit. 🥳

Happy coding and I hope you have learned something.


Top comments (0)