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
  • Project Structure
  • Image URL Generation
  • Creating URL-Friendly Strings
  • Usage in SvelteKit Components
  1. SvelteKit Server Fetching and Deployment

Utility Functions for URL Handling in SvelteKit

In this section, we'll explore two utility functions commonly used in web development for handling URLs and creating URL-friendly strings, adapted for use in a SvelteKit project.

Project Structure

First, let's consider a typical SvelteKit project structure:

my-sveltekit-project/
├── src/
│   ├── lib/
│   │   └── utils/
│   │       └── urlHelpers.js
│   ├── routes/
│   └── app.html
├── static/
└── svelte.config.js

In this structure, we'll place our utility functions in src/lib/utils/urlHelpers.js. SvelteKit provides the $lib alias to easily import from the src/lib directory.

Image URL Generation

Let's start with a function that generates URLs for images:

export function getImageUrl(imageId) {
  return `https://example.com/images/${imageId}`;
}

This getImageUrl function takes an imageId as an argument and returns a complete URL for that image. Here's how it works:

  1. The function uses a template literal (denoted by backticks `) to construct the URL string.

  2. It combines a base URL (https://example.com/images/) with the provided imageId.

  3. The ${imageId} syntax inside the template literal inserts the value of imageId into the string.

In a real SvelteKit project, you might want to use environment variables for the base URL. You can access these in SvelteKit using import.meta.env.VITE_YOUR_VARIABLE.

Creating URL-Friendly Strings

Next, let's look at a function that converts any string into a URL-friendly format:

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

The makeUrlFriendly function takes an input string and transforms it into a format suitable for use in URLs. Here's a breakdown of how it works:

  1. It uses the replace method with a regular expression to modify the string.

  2. The regular expression /[^a-zA-Z0-9]+/g matches any character that is not an alphanumeric character (a-z, A-Z, or 0-9).

  3. These matched characters are replaced with a hyphen (-).

  4. Finally, the entire string is converted to lowercase using the toLowerCase() method.

Regular expressions can be complex. In this case, ^ inside [] means "not", so [^a-zA-Z0-9] means "any character that is not alphanumeric". The + means "one or more of these characters", and g means "global" (apply to the whole string).

Usage in SvelteKit Components

To illustrate how these functions work in a SvelteKit context, let's look at an example using them in a Svelte component:

<script>
  import { getImageUrl, makeUrlFriendly } from '$lib/utils/urlHelpers';

  let imageId = '12345';
  let title = "Hello, World! This is a Test";

  let imageUrl = getImageUrl(imageId);
  let urlFriendlyTitle = makeUrlFriendly(title);
</script>

<h1>{title}</h1>
<p>URL-friendly version: {urlFriendlyTitle}</p>
<img src={imageUrl} alt="Example Image" />

In this example:

  1. We import the utility functions using the $lib alias, which SvelteKit automatically resolves to the src/lib directory.

  2. We use getImageUrl to generate a full URL for an image.

  3. We use makeUrlFriendly to create a URL-friendly version of a title.

  4. The results are then used in the component's markup.

The $lib alias is a powerful feature in SvelteKit that allows you to easily import from your src/lib directory without using relative paths. This makes your imports cleaner and more maintainable.

These utility functions are incredibly useful in web development with SvelteKit. The getImageUrl function helps maintain consistency in image URLs across your application, while makeUrlFriendly is perfect for creating clean, readable URLs from user-generated content or page titles.

Remember to adjust the base URL in getImageUrl to match your actual image hosting domain when using this in a real project. Consider using environment variables for flexibility across different environments.

PreviousPreparing a SvelteKit application for DeploymentNextFetching Directus Data from Rest API with SvelteKit

Last updated 9 months ago