skip to content

Cheatsheet: Svelte

My personal cheatsheet for Svelte.

Svelte

Await Blocks

<script>
	async function getRandomNumber() {...}
	let promise = getRandomNumber();
</script>

<button on:click={() => promise = getRandomNumber()}>
	generate random number
</button>

{#await promise}
	<p>...waiting</p>
{:then number}
	<p>The number is {number}</p>
{:catch error}
	<p style="color: red">{error.message}</p>
{/await}

Link: Logic / Await blocks - Svelte Tutorial

Add Tailwind CSS

npx svelte-add@latest tailwindcss

Link: https://github.com/svelte-add/tailwindcss

SvelteKit

SvelteKit is an application framework powered by Svelte — build bigger apps with a smaller footprint.

Creating a new SvelteKit app

npm create svelte@latest my-app
cd my-app
npm install
npm run dev -- --open

Diagnostics Check

npm run check

Provides CLI diagnostics checks for:

  • Unused CSS
  • Svelte A11y hints
  • JavaScript/TypeScript compiler errors

Install Node.js adapter

npm i -D @sveltejs/adapter-node
// file:svelte.config.js
// Make sure you use the Node.js adapter.
import adapter from "@sveltejs/adapter-node";

export default {
    ...
	kit: {
		adapter: adapter(),
	},
    ...
};

Dockerfile for SvelteKit app with Node.js adapter

# Builder
FROM node:lts-alpine AS builder
WORKDIR /app
COPY package.json package-lock.json ./

RUN npm ci
COPY . .

RUN npm run build && npm prune --production

# Docker Image
FROM node:lts-alpine

USER node:node
WORKDIR /app

COPY --from=builder --chown=node:node /app/build ./build
COPY --from=builder --chown=node:node /app/node_modules ./node_modules
COPY --chown=node:node package.json .

ENV PORT 5050
EXPOSE ${PORT}

CMD ["node", "build"]

Validation with Felte

Felte is an extensible form library for Svelte, Solid and React.

# To install felte
npm i felte

Using Zod

# To install yup + zod adapter
npm i @felte/validator-zod zod