Sveltekit - Shared Modules



Shared Modules in SvelteKit are essential for effectively organizing reusable code, and improving development efficiency and project structure. This chapter focuses on using the src/lib directory to organize shared modules and components in your SvelteKit application.

What is the $lib Alias?

The $lib alias is a built-in feature in SvelteKit that makes it easier to import files from the src/lib folder. This folder usually contains shared components, utility functions, and other code that you can use in different parts of your app.

Purpose of $lib

By using $lib, you can simplify your import statements, making your code cleaner and easier to read. Instead of dealing with complicated paths, you can refer to shared modules directly.

Document Structure

The src/lib folder in a SvelteKit project is designed to store shared code, like components, utilities, and other reusable parts. The following is a concise document structure for the src/lib directory:

my-project/
     src/
       lib/
         components/      # Reusable Svelte components
         utils/           # Utility functions
         stores/          # Svelte stores for state management
         types/           # Type definitions (if using TypeScript)
         server/          # Server-only code (accessible via $lib/server)

Using the $lib Alias

To import a file from the src/lib directory, you can use the $lib alias. This is a simple and effective method that enables us to avoid dealing with complicated paths.

Syntax

The following is a syntax for importing files using $lib alias:

<script>
  import MyComponent from '$lib/components/MyComponent.svelte';
</script>
   
<MyComponent />

Example

The following example demonstrates the use of $lib alias in our simple sveltekit Hello-World Application.

// src/lib/utils/greeting.js
export function getGreeting(name) {
    return `Hello ${name}! Welcome to SvelteKit.`;
}

// src/routes/+page.svelte
<script>
    import { getGreeting } from '$lib/utils/greetings';
    
    const message = getGreeting('World');
</script>

<h1>{message}</h1>

Output

Sveltekit-&lib
Advertisements