Documentation Shento Hendriks
Svelte / SvelteKit
Svelte / SvelteKit
  • Getting Started with SvelteKit
    • Installing SvelteKit
      • Tailwind Typography plugin
    • Base Syntax & Core Features of Svelte
      • Curly Braces & Understanding Core Syntax
      • Reactive Variables
      • Two-way-binding Shortcut
      • Using multiple components
      • Components & Communication via Props
      • Display HTML in Svelte
      • Dynamic classes
      • Using $effect
      • Working with Javascript and Rune reactivity
    • Working with Conditionals & Loops
      • Showing code conditionally in Svelte
      • Looping through arrays (lists)
      • Lists & Keys
    • Closer look at reactivity
      • Updating Arrays & Objects
      • Event Modifiers
    • Component Events
    • Best Practices
    • Adding Google Font in Tailwind and SvelteKit
    • Adding Local Fonts to SvelteKit with Tailwind
    • Prevent flicker in images
    • Enhanced Images
    • Form Submissions in SvelteKit
    • Effective SEO in SvelteKit
    • Automatic Site Maps in Svelte
    • Creating Custom Elements with Svelte, SvelteKit, and Vite
    • Creating a Svelte Library with JavaScript Functions
  • Useful Code Snippets
    • Hover effects
    • Navigation
    • Centering Items
    • Setting Footer Bottom Page
  • Installing Useful Libraries
    • Documenting Javascript with JSDocs (Crash Course)
    • Adding Lottie Animations to Svelte Application
    • SvelteKit Melt-ui
      • First Component - accordion
    • Installing Shadcn/ui Svelte
    • Getting Started with GSAP with SvelteKit
      • What is GSAP?
      • Installing GSAP & Your first animation
      • GSAP in SvelteKit
    • Installing Locomotive Scroll with Svelte 5 and SvelteKit
  • SvelteKit Server Fetching and Deployment
    • Preparing a SvelteKit application for Deployment
    • Utility Functions for URL Handling in SvelteKit
    • Fetching Directus Data from Rest API with SvelteKit
    • Fetching data from api with caching
    • Displaying Fetched Data in a Each Loop
    • Creating slug friendly urls based on query data
    • Finding correct query in api based on url slug
Powered by GitBook
On this page
  • Setting Up Your Svelte Library
  • Using Your Svelte Library
  • Publishing Your Library
  1. Getting Started with SvelteKit

Creating a Svelte Library with JavaScript Functions

This guide will walk you through the process of creating a Svelte library that includes both Svelte components and JavaScript functions. We'll also cover how to make your library available for use without Svelte.

Setting Up Your Svelte Library

Step 1: Initialize Your Project

First, let's create a new Svelte library project using the create-svelte tool.

npm create svelte@latest my-svelte-library
cd my-svelte-library
npm install

When prompted, choose the following options:

  • Select "Library project"

  • Choose whether you want to use TypeScript or not

  • You can skip additional options like ESLint, Prettier, etc., for now

Step 2: Create a Svelte Component

Let's create a simple Svelte component in your library.

<script>
  export let name = 'World';
</script>

<h1>Hello {name}!</h1>

<style>
  h1 {
    color: #ff3e00;
  }
</style>

In Svelte, the export keyword before a variable makes it a prop that can be set from outside the component. Here, name is a prop with a default value of 'World'.

Step 3: Add JavaScript Functions

Now, let's add a JavaScript file with utility functions.

export function makeUrlFriendly(input) {
  return input.replace(/[^a-zA-Z0-9]+/g, '-').toLowerCase();
}

export function capitalizeFirstLetter(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

The export keyword before each function makes them available for import in other files. You can add as many functions as you need in this file.

Step 4: Update the Library Entry Point

Now, let's update the main entry point of your library to export both the component and the functions.

export { default as MyComponent } from './MyComponent.svelte';
export * from './utils.js';

This makes your MyComponent and all exported functions from utils.js available to users of your library.

Step 5: Configure Your Package

Update your package.json file to include the necessary configuration for your library.

{
  "name": "my-svelte-library",
  "version": "1.0.0",
  "scripts": {
    "dev": "vite dev",
    "build": "vite build && npm run package",
    "preview": "vite preview",
    "package": "svelte-kit sync && svelte-package && publint",
    "prepublishOnly": "npm run package"
  },
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "svelte": "./dist/index.js",
      "default": "./dist/index.js"
    }
  },
  "files": ["dist"],
  "peerDependencies": {
    "svelte": "^4.0.0"
  },
  "devDependencies": {
    "@sveltejs/adapter-auto": "^2.0.0",
    "@sveltejs/kit": "^1.20.4",
    "@sveltejs/package": "^2.0.0",
    "publint": "^0.1.9",
    "svelte": "^4.0.5",
    "vite": "^4.4.2"
  },
  "svelte": "./dist/index.js",
  "type": "module"
}

The "default": "./dist/index.js" in the exports field makes your library available for use without Svelte. This allows users to import your JavaScript functions even if they're not using Svelte in their project.

Step 6: Build Your Library

Now you can build your library:

npm run package

This will create a dist folder with your bundled library.

Using Your Svelte Library

In a Svelte Project

Once your library is published (or if you're using it locally), you can use it in a Svelte project like this:

<script>
  import { MyComponent, makeUrlFriendly } from 'my-svelte-library';
  
  let input = '';
  let friendlyUrl = '';
  
  function handleInput() {
    friendlyUrl = makeUrlFriendly(input);
  }
</script>

<MyComponent name="Svelte Library" />

<input bind:value={input} on:input={handleInput} placeholder="Enter text">
<p>URL-friendly version: {friendlyUrl}</p>

This will render:

Hello Svelte Library!

URL-friendly version:

In a Non-Svelte Project

You can also use the JavaScript functions in a non-Svelte project:

import { makeUrlFriendly, capitalizeFirstLetter } from 'my-svelte-library';

const originalText = "hello, world! this is a test.";
const friendlyUrl = makeUrlFriendly(originalText);
const capitalizedText = capitalizeFirstLetter(originalText);

console.log(friendlyUrl); // Outputs: "hello-world-this-is-a-test"
console.log(capitalizedText); // Outputs: "Hello, world! this is a test."

Publishing Your Library

To publish your library to npm, use the following command:

npm publish

Make sure you're logged in to npm and have a unique package name before publishing.

By following this guide, you've created a versatile Svelte library that includes both Svelte components and JavaScript functions. This library can be used in Svelte projects and non-Svelte projects alike, making it a flexible tool for a wide range of applications.

PreviousCreating Custom Elements with Svelte, SvelteKit, and ViteNextUseful Code Snippets

Last updated 9 months ago