Learn SvelteKit by Building a Reddit Clone Application

Responses (1)

Christoph Sturm3 months ago

is there ever going to be a part 2?


SvelteKit is a serverless-first framework for building high-performance, web applications with Svelte. Newcomers to Svelte can think of SvelteKit as Next.js or Nuxt.js, but for Svelte. First announced in October 2020, SvelteKit entered public beta in March 2021 and is the successor of Sapper, a now deprecated Svelte-based framework. With the Svelte team abandoning sveltejs/template and sveltejs/sapper-template, SvelteKit became the de-facto framework for building any type of web application (of any size) with Svelte. SvelteKit inherits many of Sapper's functionality and features:

  • Code-Splitting

  • Filesystem-Based Routing

  • Server-Side Rendering and Static-Site Generation (With Client-Side Hydration)

  • Offline Support

  • Prefetching Pages

However, the Svelte team designed SvelteKit to address Sapper's shortcomings:

  • SvelteKit adopts unbundled development into its development workflow. Under-the-hood, SvelteKit leverages Vite to spin up a development server that transforms and serves source code (over native ESM) on-demand. Unlike Webpack, which Sapper uses as its bundler, Vite does not re-bundle/rebuild chunks of the application on each file change; only the file that changes gets rebuilt. Since dependencies get pre-bundled with esbuild, Vite's cold-start time is significantly less than other tools' cold-start times. By taking advantage of modern browsers' support for native ESM, Vite's Hot Module Replacement (HMR) is fast regardless of application size. Originally, SvelteKit leveraged Snowpack for unbundled development, but Snowpack was later dropped for Vite once Vite became framework-agnostic.

  • SvelteKit provides the option of partial pre-rendering. A subset of the application can be pre-rendered as static files at build time (static-site generation), and another subset of the application can be dynamically rendered upon incoming requests (server-side rendering).

  • SvelteKit embraces serverless platforms as first-class deployment targets. SvelteKit's Adapter API lets you create an adapter (small plugin) that exports the built application for a specific platform. An adapter tailors and optimizes the built application to work seamlessly on a specific platform. SvelteKit's ecosystem already has adapters for popular serverless platforms (e.g., @sveltejs/adapter-cloudflare-workers for Cloudflare Workers, @sveltejs/adapter-vercel for Vercel and @sveltejs/adapter-netlify for Netlify) and static site hosting services (e.g., @sveltejs/adapter-static for GitHub Pages and other related services).

  • SvelteKit's build script (vite build) generates a production version of the application that's agnostic to deployment targets. Sapper has two npm scripts that build a production version of the application: build and export. build outputs it as a standalone Node.js application that can only be ran with a Node.js server, whereas export outputs it as a static site. Based on the adapter added to the SvelteKit project's configuration, SvelteKit's build script can perform any one of these tasks:

    • @sveltejs/adapter-node - Creates a standalone Node.js server that hosts the application. This adapter corresponds to Sapper's build script.

    • @svelte/adapter-static - Pre-renders the application as a collection of static files. This adapter corresponds to Sapper's export script.

    SvelteKit's build script can adapt the application to any environment as long as you add the appropriate adapter to the SvelteKit project's configuration. Sapper applications can run on other platforms with the help of unofficial, third-party tools like vercel-sapper for Vercel. Unlike SvelteKit, Sapper lacks an API for adapting an application for different platforms. Therefore, given that each of these tools comes with its own unique implementation and its own set of instructions for integration into an application, developing and maintaining these tools is incredibly difficult.

Although the road to v1.0 remains in progress, you can still build production-grade, SEO-friendly applications with the SvelteKit beta. The best part of SvelteKit is the ability to build Next.js-like applications with an amazing developer experience and with Svelte, which exceeds React in terms of performance and size. Svelte's compiler turns Svelte components (written with an intuitive, declarative API) into efficient JavaScript.

Below, I'm going to show you:

  • How to scaffold a SvelteKit application.

  • How to navigate the codebase of a SvelteKit application.

  • How to build a Reddit clone application with SvelteKit.

By the end of this tutorial series, you will have built a full-functional Reddit clone application with SvelteKit and TailwindCSS:

Preview of Reddit Clone Application

Installation and Setup#

To get started, run the following command to create a new SvelteKit project:

The npm create command is an alias for the npm init command. This command gets transformed to the command npm exec [email protected] <project-name>, which remotely fetches the create-svelte CLI executable and runs it to create a new SvelteKit project.

The CLI tool will present a series of prompts that determine how you want to set up the project:

  1. Which Svelte app template? - Select the Skeleton project option. This scaffolds the new SvelteKit application with a barebones template.

  2. Add type checking with TypeScript? - Select the Yes, using TypeScript syntax option. This adds TypeScript support to the project.

  3. Add ESLint for code linting? - Answer Yes. This adds linting to the project.

  4. Add Prettier for code formatting? - Answer Yes. This adds code formatting to the project.

  5. Add Playwright for browser testing? - Answer Yes. This adds E2E testing to the project.

After the project has been created, change your current directory to the project's directory and install the dependencies.

When you open the package.json file, you will notice SvelteKit already provides several npm scripts:

  • dev - Spins up a development server that runs the application. Anytime you save changes to a file, the development server picks up those changes and makes precise updates to your application in the browser via lightning-fast HMR. No full page refresh. No resetting the application state.

  • build - Generates a production version of the application and runs the adapter that's added to the SvelteKit project's configuration.

  • package - Packages the Svelte components located in the src/lib directory as a Svelte component library. This script outputs the Svelte component library to a package directory. If you choose to publish the Svelte component library, then run the command npm publish ./package.

  • preview - Previews the production version of the application on your local machine.

  • prepare

    - Auto-generates files that SvelteKit needs to run the built application and places them in the



    • generated/client-manifest.js - Powers the router. It maps routes to their corresponding Svelte components.

    • generated/client-matchers.js - Collects any matchers that are defined within the src/params directory. These matchers ensure SvelteKit can check route parameters and match to the correct route.

    • generated/root.svelte - Serves as the parent component of the layout components defined in the src/routes directory (hierarchically, where layout components get rendered).

    • runtime - Contains the files needed for running the SvelteKit client and server. These files originate from the node_modules/@sveltejs/kit/assets directory.

    • types - Contains the type definitions for each route.

    • tsconfig.json - Contains the base TypeScript configuration for a SvelteKit project. The tsconfig.json in the root of the project directory extends from this auto-generated tsconfig.json file. This allows you to customize the TypeScript configuration to your own liking/specifications without messing up the base TypeScript configuration that's needed for a TypeScript-based SvelteKit project to work properly.

    Anytime you run the npm install command, npm will execute the prepare script (npm) to regenerate these files (as part of the life cycle scripts). Running the npm run dev command or npm run build command will also regenerate these files.

Other npm scripts get added based on the additional tooling that you told the SvelteKit CLI to add to the project:

  • test (Playwright) - Runs E2E tests.

  • check (TypeScript) - Checks for type errors in Svelte and TypeScript files.

  • check:watch (TypeScript) - Checks for type errors in Svelte and TypeScript files anytime a file change happens.

  • lint (ESLint/Prettier) - Checks if files are formatted correctly (prettier --check) and if files contain any potential bugs or problematic patterns (eslint).

  • format (Prettier) - Formats files based on the Prettier configuration.

To verify that the application runs properly, start up the development server and visit the application at http://localhost:5173:

Currently, there is not much on the page, but that will change as you progress further in this tutorial.

Overview of a SvelteKit Project's Directory and File Structure#

Now that you know how to locally run a SvelteKit application, let's take a look at the remaining files and directories that make up a SvelteKit project.

The following is the directory and file structure of a barebones SvelteKit project:

Within the root of the project directory, you will find the following files:

  • .gitignore - Specifies the files and directories that should not be tracked by Git. Ideally, you want Git to ignore build artifacts and files that contain sensitive information (e.g., credentials for APIs).

  • .npmrc - Configures npm. This file only sets the configuration setting engine-strict to true. This tells npm to not install any npm package that claims to not be compatible with the version of Node.js installed on the running machine.

  • .prettierignore (If You Added Prettier) - Specifies the files and directories that should not be formatted by Prettier. Most of these files and directories will also likely be listed in .gitignore.

  • .prettierrc (If You Added Prettier) - Configures Prettier. SvelteKit automatically provides a Prettier configuration that specifies to:

    • useTabs: true - Use tabs instead of spaces for indentations.

    • singleQuote: true - Use single quotes instead of double quotes.

    • trailingComma: "none" - Omit trailing commas.

    • printWidth: 100 - Wrap lines when the line length reaches (or exceeds) 100 characters.

  • package.json - Contains metadata about the project (e.g., its name, entrypoint, dependencies, etc.).

  • playwright.config.ts (If You Added Playwright) - Configures Playwright. SvelteKit automatically provides a Playwright configuration that runs tests after spinning up the preview of the production version of the application on localhost:4173.

  • README.md - Serves as a simple form of documentation for the project.

  • svelte.config.js - Configures the SvelteKit project. `js import adapter from '@sveltejs/adapter-auto'; import preprocess from 'svelte-preprocess';

    /* @type {import('@sveltejs/kit').Config} / const config = { // Consult https://github.com/sveltejs/svelte-preprocess // for more information about preprocessors preprocess: preprocess(),

    kit: { adapter: adapter() } };

    export default config; ` By default, SvelteKit sets the adapter option to an adapter that automatically selects one of three adapters to build the application with based on the application's current environment:

  • tsconfig.json (If You Added TypeScript) - Configures TypeScript. This TypeScript configuration extends the TypeScript configuration that's generated inside of the .svelte-kit directory. This ensures that the SvelteKit project always has the minimum configuration required for it to run even if you customize the TypeScript configuration.

  • vite.config.js - Configures Vite. `js import { sveltekit } from '@sveltejs/kit/vite';

    /* @type {import('vite').UserConfig} / const config = { plugins: };

    export default config; ` By default, SvelteKit only adds the SvelteKit Vite plugin to the Vite configuration.

When you look inside the src directory, you find the following files and directories:

  • app.d.ts - Contains type definitions for the application. `ts ///

    // See https://kit.svelte.dev/docs/types#app // for information about these interfaces // and what to do when importing types declare namespace App { // interface Locals {} // interface Platform {} // interface Session {} // interface Stuff {} } ` If you uncomment and populate any of the interfaces declared within the App namespace, then you will unlock type safety for various SvelteKit objects like event.locals (Locals) and session (Session).

  • app.html - Contains the application's page template markup. `html

  • routes - Contains the application's layouts, pages and endpoints.

    • routes/index.svelte - The page component that corresponds to the / route. `svelte

The src directory can also have the following optional files and directories:

  • lib - Contains library code (e.g., a Svelte component library) that can be packaged for distribution via the package npm script.

  • params - Contains the application's param matchers.

  • hooks.js - Contains the application's hooks.

  • service-worker.js - Contains the application's service worker.

The static directory contains all of the application's static assets, such as favicon.png (the SvelteKit project already comes with a default favicon.png file) and sitemap.xml.

The tests directory contains any E2E tests that should be ran by Playwright.

Next Steps#

Continue on to the second part of this tutorial.