Read if:
Complete Example:
Introduction
I love SvelteKit, there are many reasons for that but on of them is svelte-kit inbuilt packaging module.
The SvelteKit documentation states that you can use the SvelteKit to build component libraries as well as apps. So I'm going to tell you every single step including publishing the package to npm.
Setting Up SvelteKit
MyComponentsLibrary
~ npm init svelte@next MyComponentsLibrary
~ cd MyComponentsLibrary
~ npm i
~ npm run dev
As you can see above dir tree
there is one folder inside src
named lib
. This is the place where you going to make your components.
Button.svelte
and index.js
file in lib
directory. Which will going to look like this:As you can see i have added both the file and now we gonna make our Button Component.
Code Button.svelte
<script lang="ts">
export let label = '';
export let disabled = false;
let props = { ...$$restProps };
</script>
<button class={props.class} {disabled} style={props.style} props on:click on:*>
{label}
<slot />
</button>
Now, I'll explain what's happening here :
As you can see we are using export let label, this line means where we use Button component we can pass label value in that. same for disabled.
{ ...$$restProps } this is a special thing in SvelteKit. If you pass extra parameter to component you can access them using this inside the component. As you can in button tag where I'm passing style and classes to it.
<slot />
means what ever you write between your component tag will be render on the web page.
Now we are done with Button.svelte
.
Code index.js
export { default as Button } from './Button.svelte';
Setting Up package.json
"name": "svexy-ui"
. This will be the package name of your library."exports": {
".": "./index.js"
}
. This is root file."module": "index.js"
. This is main file.For more info please google them
exports in package.json
andmodule in package.json
.
Setting Up svelte.config.js
package: {
dir: 'folder that will be generated'
}
in kit.You can find all code in the live example.
Packaging on our components
svelte2tsx
using npm
.npm
run package
in your terminal. This will generate a dir in root of the project.svexy-ui
. This contains you package that you can publish on npm
.It contains your index.js
file with lib
directory files with package.json
and with a README.md
.Publishing to NPM
If you are ready you can publish it on npm
. You must log in to npm
from your terminal using npm
login.
Change the directory to package and run npm
publish command.
cd svexy-ui
npm publish --access public
...
That's all we have to do and you gonna have your svelte component library on npm
.
Resources
This is me writing for you. If you wanna ask or suggest anything please put it in comment.
Our service will help you design and develop your product.