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

<script>
    let counter = 0;

    const handleClick = () => {
        counter += 1;
    };
</script>

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

<style>
    button {
        color: red;
    }
</style>

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": [
    "dist",
    "src"
],
"repository": "https://github.com/username/my-svelte-component",
"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

.gitignore
LICENSE
README.md

Testing

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

<script>
  import MyComponent from "my-svelte-component";
</script>

<h1>MyComponent</h1>
<MyComponent />

Publish to GitHub

Create new repository on GitHub, then

git init
git add .
git commit -m "Initial commit"
git remote add origin git@github.com:username/my-svelte-component.git
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

TODO

Type definition files not implemented yet, coming soon.

© Andy Gock 2009−2022