Create a Svelte component module

23 October, 2022Web Development

Using pnpm, Svelte, rollup.js, create a Svelte component module, test it, and publish to npm.

This is a quick cheat sheet for developers without the distractions. Modify as needed.

Create component

mkdir my-svelte-component
pnpm init
pnpm install -D rollup rollup-plugin-node-resolve rollup-plugin-svelte rollup-plugin-postcss postcss svelte
mkdir src

Create src/index.js

import MyComponent from './MyComponent.svelte';
export default MyComponent;

Create src/MyComponent.svelte

    let counter = 0;

    const handleClick = () => {
        counter += 1;

<button on:click={handleClick}>{counter}</button>

    button {
        color: red;

Edit package.json

"main": "dist/index.js",
"type": "module",
"svelte": "src/index.js",
"name": "my-svelte-component",
"version: "0.1.0",
"scripts": {
    "build": "rollup -c",
    "dev": "rollup -c -w"
"files": [
"repository": "",
"license": "MIT",

Create rollup.config.js

import svelte from 'rollup-plugin-svelte';
import resolve from 'rollup-plugin-node-resolve';
import postcss from "rollup-plugin-postcss";

const pkg = require('./package.json');

export default {
  input: "src/index.js",
  output: [
    { file: "dist/index.js", format: "umd", name: "MyComponent" },
  plugins: [svelte(), postcss(), resolve()],

Add other useful files as desired



Test locally in new Svelte project

pnpm create vite@latest myapp-test --template svelte
cd myapp-test
pnpm install
pnpm link /path/to/my-svelte-component
pnpm dev

Instead of linking, you could also use install directly but without HMR.

pnpm install /path/to/my-svelte-component

Edit ./src/App.svelte

  import MyComponent from "my-svelte-component";

<MyComponent />

Publish to GitHub

Create new repository on GitHub, then

git init
git add .
git commit -m "Initial commit"
git remote add origin
git branch -M master
git push -u origin master

Publish to npm

Publish the package to npm.

npm publish

To update

npm version <patch|minor|major>
npm publish


Type definition files not implemented yet, coming soon.

© Andy Gock 2009−2022