Sveltekit tutorial cover image
In case you missed the announcement, Sapper is being replaced by a much newer framework - SvelteKit. This tutorial looks at some of the reasons influencing the change from Sapper to SvelteKit, how to get started using SvelteKit to build web apps, how deployment works, and more.  
GeneralArticlesFrontend Development

Exploring SvelteKit : A new approach to building Svelte Apps

7 Mins read

In case you missed the announcement, Sapper is being replaced by a much newer framework – SvelteKit. This Sveltekit tutorial looks at some of the reasons influencing the change from Sapper to SvelteKit, how to get started using SvelteKit to build web apps, how deployment works, and more.  

Intended Audience:

This SvelteKit tutorial is aimed at developers who already have a basic understanding of svelte alongside some familiarity with Javascript frontend frameworks in general.  Hopefully, this article should be easy to understand if you know how to use Svelte and/or Sapper to build web apps. 

What is Svelte and SvelteKit

If you’re not familiar with svelte already, there’s no better way to explain it than from this quote on the documentation site itself: 

Svelte is a radical new approach to building user interfaces. Whereas traditional frameworks like React and Vue do the bulk of their work in the browser, Svelte shifts that work into a compile step that happens when you build your app.
Instead of using techniques like virtual DOM diffing, Svelte writes code that surgically updates the DOM when the state of your app changes.”
Svelte is a component-based Javascript framework – much like React, Vue, or angular and is used for building web applications in Javascript.

https://svelte.dev/

SvelteKit, on the other hand, is a svelte-based framework for developing web apps. Sveltekit extends the capability of Svelte by offering enhancements such as Server-Side Rendering (SSR), a File-based routing system, client-side hydration, and some other exciting features that we will take a look at shortly below. 

Why the switch from Sapper to SvelteKit 

In an introductory blog post published by Richard Harris, who created Svelte itself, some of the reasons that influenced the switch from Sapper to SvelteKit are mentioned below:

  • The Sapper project, which was started in 2017, had grown large over the years and had grown to be somewhat unkempt. Hence, a need to rewrite the codebase arose.
  • Principles around web development have changed drastically over the years; as a result, there was a need to have something freshly built based off of the current trends and practices in vogue.
  • Apart from being a bit out of vogue, using Sapper seemed a somewhat complicated process that could be made simpler. First, the similarity between the naming of the sveltejs/template and sveltejs/sapper-template seemed slightly confusing for developers not already familiar with the svelte ecosystem. 
  • Also, the prospect of having a single recommended way to built apps in svelte seemed like something that would spur positive impact. It would simplify the onboarding process for new projects and reduce the burden of maintaining and providing support for apps built in svelte.
Also Read:  Deploying and Managing Your Machine Learning Pipeline with Terraform and Doppler

Under the hood, SvelteKit is powered by Snowpack, A modern frontend build tool that offers faster lighter, and less complex builds in order to provide a smoother development experience when writing web apps in JavaScript.  When developing apps previously with Sapper, developers have the option to use either Rollup or Webpack, two bundlers Richard himself notes are not as impressive a rollup. 
Away from the technicality now, let’s have a practical look at SvelteKit in action by building a simple website with a basic navigation and styling system. 

How to Setup SvelteKit 

To set up a project with SvelteKit, you must have NPM, a package manager that ships along with NodeJs. If you do not have NodeJS setup on your computer, head over to the downloads page to install a suitable version. Once you have NPM installed, run the following commands to scaffold a SvelteKit project, navigate into the folder to install the necessary dependencies, and subsequently start a development environment for your application to run on. 


npm init svelte@next project-name
cd my-app
npm install
npm run dev

Note: If prompted by the installer to select an installation type, you should choose the skeleton scaffolding as that’s what we’d be using in this example. 

Components Composition and Layouts in Sveltekit

Like any component-based framework, Svelte allows you to define independent pieces of code that can be pieced together to make up your app’s overall interface and so does SvelteKit.  In Svelte, you can reuse elements by importing them into another component, as seen in the example snippet below. 


<script>
import ReusableComponent from './ResuableComponent.svelte';
</script>

<p>I'm injecting the content of my reusable component below</p>
<ReusableComponent/>

When importing traditional components in Svelte, you should note that each component’s styling is scoped internally. This implies that styling applied to an imported component will affect the component alone. 

Styling in SvelteKit

Styling your SvelteKit apps is pretty much the same process as in your regular HTML codebase. You can reference external CSS files in the head tag of your app.html and apply styles by attaching a class, id, or whatever selector you deem proper.  
In our demo project, we’d reference the Litera stylesheet from bootstwatch.com, a website that provides free bootstrap-based starter css templates. 

Also Read:  What is SSO - A Free 2 Minute Guide to understanding Single-Sign-On.

To do this, let’s add the following to the <head> </head> tag of our src/app.html file 


<link rel="stylesheet" href="https://bootswatch.com/5/litera/bootstrap.min.css" />  

Defining App Layouts in a SvelteKit project

When building a web app, for example, you would need to write a header and footer for most – if not all parts of your app. SvelteKit makes this a painless process in its architecture by allowing you to create and extend layout components. To define a layout component that will be inherited by every page in your app, you need to create a __layout.svelte file in your project’s src/routes folder. This behavior can be customized – again, by modifying your project’s svelte.config.js file.

SvelteKit allows you to define markup and styles applied to every page or component inheriting the __layout.svelte file. You can inject the content of the inheriting page in your layout file by adding <slot> </slot> tags. 

How to build a navigation system in Sveltekit

Let’s create a __layout.svelte in our app’s src/route folder in order to define our navigation bar. Once you’ve created the file, put the following block of code in it and save it to see your changes applied instantly in the browser.


<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
  <div class="container-fluid">
    <a class="navbar-brand" href="/">Sveltekit</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse" id="navbarColor01">
      <ul class="navbar-nav me-auto">
        <li class="nav-item">
          <a class="nav-link active" href="./">Home
            <span class="visually-hidden">(current)</span>
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="/features">Features</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="/pricing">Pricing</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="/about">About</a>
        </li>
      </ul>

    </div>
  </div>
</nav>


<div class="container">

  <!-- Pages will be injected below -->
    <slot></slot>
</div>

Routing in SvelteKit

Like in NextJs and other popular SSR solutions, SvelteKit makes use of a file-based routing system. When working with SvelteKit, pages are stored by default in the src/routes folder, a behavior which, of course, can be tweaked according to your demands by simply modifying the svelte.config.js file. After installing our fresh svelte kit project and setting the layout, we can open up the routes folder and then begin creating our pages.  

Our website will contain the following pages whose content will be contained in the accompanying files.

  • Home – index.svelte (already created 🙂 )
  • About – about.svelte
  • Features – features.svelte
  • Pricing – pricing.svelte

The markup for the index page should look like this:


<!--  routes/index.svelte -->
<!-- Index page -->
<svelte:head>
    <title>Home Page</title>
</svelte:head>
<h1>Home Page</h1>
<p>This is the home page. Click <a href="/about">here</a> to go to the about page.</p> 

Similarly, put the following block of code in the about.svelte file.


<!-- about page -->
<svelte:head>
    <title>About</title>
</svelte:head>
<h1>About Page</h1>
<p>This is the about page. Click <a href="/">here</a> to go to the home page.</p>

Do likewise the features.svelte file


<!-- features page -->
<svelte:head>
    <title>About</title>
</svelte:head>
<h1>Features</h1>
<p>This is the features page. Click <a href="/">here</a> to go to the home page.</p>

The Pricing page as well : )


<!-- pricing page -->
<svelte:head>
    <title>About</title>
</svelte:head>
<h1>Pricing</h1>
<p>This is the Pricing page. Click <a href="/">here</a> to go to the home page.</p>

Once the markup for our pages is set, head over to the browser to see our mini-website in action. 

Also Read:  Adding Event Listeners in Javascript
sveletkit tutorial - navigation in action
Our navigation in action

ServerSide rendering in SvelteKit

One of the key features of SvelteKit as a framework is the availability of Server-side Rendering or SSR for short. SSR enables the content of your app to be rendered from the server as opposed to rendering from the client’s browser. SSR not only enables search engines to smoothly read and navigate the content of our app, but it also allows users with low-end devices to access our apps better.  SvelteKit uses a process known as hydration to first render the content of the page as HTML from the server then perform a re-render to make it reactive.

Deployment

SvelteKit helps simplify the deployment process through the provision of several packages or plugins known as adapters. These adapters act on your codebase and generate files suitable for deploying your app to the target environment.  A few of these adapters which I believe are worthy of note include: 

  • Adapter Vercel: For deploying your app to the Vercel hosting platform.
  • Adapter Netlify: Yes, you guessed right, made for deploying your app on the Netlify platform. 
  • Adapter Static: For deploying your app to a traditional static file compatible hosting service like GitHub pages, shared hosting servers, and the likes. 

Conclusion

We’ve come so far in this sveltekit tutorial already and I hope you’ve learned something regarding svelte and sveltekit in general.

Compared to the traditional way of building web apps using Sapper, SvelteKit removes the bottleneck of setting up your development environment so you can build web applications faster. Although SvelteKit is still in beta, you can explore it and use it for your next Svelte project with some of the concepts you learned here.  

Read Next: How to remove event listeners in Javascript.

11 posts

About author
Oluwaseun Raphael Afolayan is an Established Software craftsman and Technical Writer with over 5 years of experience building and documenting tech solutions for startups. He enjoys running around sweaty PUBG-mobile lobbies in his spare time.
Articles
Related posts
Mobile DevelopmentFrontend Development

Using SVGs properly in React Native

2 Mins read
Using SVGs in a React Native project can take your app’s design to the next level. SVGs are perfect for icons, logos,…
ArticlesBackend DevelopmentGeneral

MD5 vs SHA1 - A comparision

3 Mins read
When it comes to encryption, there are a few different algorithms that you can use. Two of the most popular ones are…
Frontend Development

Supercharging Javascript Arrays With the Spread Operator

1 Mins read
The spread operator can turn the elements of an array into elements of a function call or into elements of another array…
Subscribe to more programming tutorials

Be the first to get notifications of byte-sized articles to make you a better programmer.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

×
Frontend DevelopmentGeneral

Adding Event Listeners in Javascript