Svelte.js Cheatsheet
Tags: svelte, webdev, javascript, beginners
Published: 2023-09-07 01:46:55



Svelte.js is a modern JavaScript framework that simplifies web development by compiling components at build time rather than running them in the browser. This cheatsheet provides a quick reference to key concepts and features in Svelte.js for developers at beginner and intermediate levels.

## Getting Started

### Installation

To start using Svelte.js, you need to set up a development environment. You can create a new Svelte project using the official template:

```bash
npm create svelte@latest myapp
cd myapp
npm install
npm run dev
```

### Svelte Components

Svelte applications are built using components. Each component is defined in a `.svelte` file and encapsulates its HTML, CSS, and JavaScript logic.

```html
<!-- HelloWorld.svelte -->
<script>
  let name = 'Svelte';
</script>

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

<style>
  h1 {
    color: blue;
  }
</style>
```

## Data Binding

### Variables

You can declare and use variables in your Svelte components. Variable updates automatically trigger reactivity.

```html
<script>
  let count = 0;
</script>

<button on:click={() => count += 1}>Increment</button>
<p>Count: {count}</p>
```

### Two-Way Binding

You can achieve two-way binding using the `bind` directive:

```html
<script>
  let name = 'Svelte';
</script>

<input bind:value={name} />
<p>Your name is: {name}</p>
```

## Conditionals and Loops

### Conditional Rendering

You can conditionally render elements using `{#if}` and `{:else}`:

```html
{#if loggedIn}
  <p>Welcome, {user.name}!</p>
{:else}
  <p>Please log in.</p>
{/if}
```

### List Rendering

You can loop through arrays using `{#each}`:

```html
<ul>
  {#each items as item}
    <li>{item}</li>
  {/each}
</ul>
```

## Events and Event Handling

### Event Listeners

You can listen for DOM events and handle them with functions:

```html
<button on:click={handleClick}>Click Me</button>

<script>
  function handleClick() {
    alert('Button clicked!');
  }
</script>
```

### Event Modifiers

Svelte provides event modifiers like `preventDefault` and `stopPropagation`:

```html
<a href="/example" on:click|preventDefault={handleClick}>
  Clicking this link won't navigate.
</a>
```

## Component Communication

### Props

You can pass data from parent to child components using props:

```html
<!-- Parent.svelte -->
<script>
  let message = 'Hello from Parent!';
</script>

<Child message={message} />

<!-- Child.svelte -->
<script>
  export let message;
</script>

<p>{message}</p>
```

### Custom Events

Child components can communicate with parents using custom events:

```html
<!-- Child.svelte -->
<script>
  import { createEventDispatcher } from 'svelte';

  const dispatch = createEventDispatcher();

  function notifyParent() {
    dispatch('customEvent', 'Data from Child');
  }
</script>

<button on:click={notifyParent}>Notify Parent</button>
```

```html
<!-- Parent.svelte -->
<script>
  let dataFromChild = '';

  function handleCustomEvent(event) {
    dataFromChild = event.detail;
  }
</script>

<Child on:customEvent={handleCustomEvent} />
<p>Data from Child: {dataFromChild}</p>
```

## Lifecycle Methods

Svelte components have lifecycle methods like `onMount`, `beforeUpdate`, and `afterUpdate`:

```html
<script>
  import { onMount } from 'svelte';

  onMount(() => {
    console.log('Component mounted');
  });
</script>
```

## Stores

Svelte provides stores for shared state management:

```html
<script>
  import { writable } from 'svelte/store';

  const count = writable(0);

  function increment() {
    $count += 1;
  }
</script>

<button on:click={increment}>Increment</button>
<p>Count: {$count}</p>
```

## Routing

You can implement client-side routing in Svelte using libraries like `svelte-routing`.

## CSS

Svelte supports scoped styles using `<style>` blocks within components.

## Dev Tools

Svelte has a browser extension for debugging and inspecting components.

## Conclusion

Svelte.js offers a straightforward and efficient way to build web applications with a focus on reactivity and simplicity. This cheatsheet covers essential concepts and features to help beginners and intermediate developers get started with Svelte development.

*Estimated Reading Time: 6 minutes*