October 6, 2022

Robotic Notes

All technology News

Exploring SvelteKit in 2022 by Building a Portfolio Website

9 min read


The team at svelte introduced Sveltekit a few months ago. It’s a newer framework that replaces Sapper. It is the fastest way to build svelte apps with beautiful development experiences and flexible filesystem-based routing. This article will explore how Sveltekit works by building a sample portfolio website with every necessary update in the framework. You will learn all the fundamental concepts on building a web app with Sveltekit, why the switch from Sapper to Sveltekit, and how to consume REST API in Sveltekit by building a demo blog within your app. Additionally, you will learn how to deploy Sveltekit application on Netlify.

What is Sveltekit

For those new to Svelte, according to svelte website:

1Svelte is a radical new approach to building user interfaces. Whereas traditional

2frameworks like React and Vue do the bulk of their work in the browser, Svelte shifts that

3work into a compile step that happens when you build your app.

4Instead of using techniques like virtual DOM diffing, Svelte writes code that surgically

5updates the DOM when the state of your app changes.

6Svelte is a component-based Javascript framework - much like React, Vue, or angular and is

7used for building web applications in Javascript.

On the contrary, Sveltekit is a framework for building svelte apps of all sizes; it enables you to build more significant apps with a smaller footprint. It comes with a beautiful development experience, flexible filesystem-based routing, Server-Side Rendering (SSR), client-side hydration, and some other unique features.

Reasons for Switching from Sapper to Sveltekit

Richard Harris, the creator of Svelte, mentions some of the reasons that influenced the switch from Sapper to sveltekit, which are:

  • Sapper appeared to be a bit complicated; the distinction between sveltejs / template and sveltejs / sapper-templated seems slightly confusing, particularly for newcomers to Svelte.
  • Since the Sapper project started in 2017, the codebase has become a little unkempt over the years. And because the web has changed drastically over the years, there comes a need to rethink a newer approach.
  • Also, the idea of ​​having a single recommended way of building apps with svelte will bring significant benefits. It would simplify the onboarding process, reduce maintenance, and support burden.

Getting Started with Sveltekit

Sveltekit removes all the bottlenecks of building modern web apps; it does all the boring stuff for you while you concentrate on the creative part. It is powered by Snowpack under the hood, a lightning-fast frontend build tool designed for the modern web. It uses Vite with Svelte plugin to provide a lightning-fast and feature-rich development experience with Hot Module Replacement (HMR). Changes to your code are instantly reflected in the browser.

To set up a project with Sveltekit, you must have NodeJS set up on your computer. Please run the following command below to scaffold our sveltekit demo project, then go into the folder to install all necessary dependencies.

1npm init svelte@next my_portfolio_website

2cd my_portfolio_website

3npm install

4npm run dev

The first command will scaffold a new project in the ‘my_portfolio_website’ directory asking you if you’d like to set up some basic tooling such as TypeScript. Kindly choose ‘No’ because we won’t use Typescript in this project. The subsequent commands will then install its dependencies and start a server on localhost: 3000.

Below is a sample demo of what we are building.

Sample Demo

To follow along with this article, you can check out the GitHub repo.

Pages and Component Composition

One of the fantastic features of Sveltekit is its filesystem-based router. It means that the structure of your codebase defines the structure of your application. We have two types of routes which are: pages and endpoints. Pages generally generate HTML, CSS, and JavaScript needed for the page to be displayed to the user, while Endpoints run only on the server (or when you build your site, if prerendering).

Like any other component-based framework, Pages are Svelte components written in .svelte files (or files with an extension listed in config.extension. When users first visit the application, they will be served a server-rendered version of the page in question by default. From there, navigating to other pages is handled entirely by the client .

The filename determines the routes. For example, src / routes / index.svelte is the root of our demo site.

Open the project folder with the code editor of your choice and navigate to src / routes / index.svelte. Insert the following code below:

1<!-- src/routes/index.svelte -->

2<svelte:head>

3 <title>David Adeneye</title>

4</svelte:head>

5

6<div class="container">

7 <div class="info">

8 <div class="animate-background">

9 <div class="container info-container">

10 <div class="info-text">

11 <h1,

12 <p class="animate-text-1">School-taught Computer Scientist,</p>

13 <p class="text-2">Self-taught Software Engineer</p>

14 </h1>

15 </div>

16 <h2 class="subtitle">

17 On a mission to help SMEs across the globe do businesses

18 seamlessly and digitally.

19 </h2>

20 <div style="color:black" class="scroll-button animate-scroll" tabindex="0">

21 <a href="/about">Click Here</a><div class="arrow"></div>

22 </div>

23 </div>

24 </div>

25 </div>

26</div>

27

28<div class="background-div"></div>

The <svelte:head> tag element in the second line allow you to insert elements inside the <head> of your document. The rest of the code is our Html page structure for the index page. The next section will look into how styling works in Sveltekit.

Styling our app in SvelteKit

The way styling work in Sveltekit is pretty much the same process as our regular HTML & CSS projects. You can reference external CSS files or root styles applied to all pages in the head tag of your app.html and apply the styles by attaching selectors to document tags.

To style our index.svelte files above, add the following style beneath the last code.

1<style>

2 .info {

3 text-align: center;

4 position: relative;

5 }

6

7 .info-container {

8 height: 100%;

9 display:flex;

10 flex-direction: column;

11 justify-content: center;

12 text-align: left;

13 align-items: start;

14 }

15

16 .container {

17 max-width: 1400px;

18 margin: 190px 0 0 2.5rem;

19 }

20

21 .info h1 {

22 font-size: 4rem;

23 margin: 0;

24 }

25

26 .info h1 p {

27 position: relative;

28 font: inherit;

29 margin: 0;

30 text-align: left;

31 line-height: 130%;

32 width: fit-content;

33 font-weight: 800;

34 letter-spacing: -0.03em;

35 }

36

37 .info h2 {

38 max-width: 65ch;

39 font-weight: 200;

40 margin-top: 0.50rem;

41 }

42

43 .background-div {

44 background-color: var(--background);

45 width: 100%;

46 height: 56vh;

47 margin: -155px auto;

48 }

49

50

51 .info .info-text {

52 position: relative;

53 }

54

55 .scroll-button {

56 display: flex;

57 border: none;

58 outline: none;

59 cursor: pointer;

60 }

61

62 .scroll-button .arrow {

63 margin-left: 0.50rem;

64 }

65</style>

Also, to have our global styling work on other pages, open the app.html and insert the following styling beneath the html closing tag.

1<style>

2 body {

3 background-position: left top;

4 font-family: "Inter", sans-serif;

5 margin: 0;

6 background-repeat: no-repeat;

7 }

8

9 * {

10 box-sizing: border-box;

11

12 }

13

14 a {

15 text-decoration: none;

16 color: black;

17 }

18

19 :root{

20 --background: #ecebe8;

21 }

22

23

24 nav {

25 position: sticky;

26 top: 0;

27 left: 0;

28 right: 0;

29 margin: 0 80px 0 80px;

30 padding-top: 2rem;

31 padding-bottom: 2rem;

32 }

33

34 nav .nav-container {

35 display: flex;

36 justify-content: space-between;

37 align-items: center;

38 }

39

40 .nav-links {

41 display: flex;

42 justify-content: flex-end;

43 align-items: center;

44 margin: -1em 0;

45 flex: 1 0 auto;

46 }

47

48 .nav-links .link {

49 position: relative;

50 margin: 1em;

51 font-size: 0.85rem;

52 letter-spacing: 1px;

53 color: black;

54 }

55

56 .nav-logo {

57 position: relative;

58 line-height: 1;

59 font-size: 1.1rem;

60 color: black;

61 }

62</style>

Also, note that each component styling is internally scoped when importing components in Svelte. It means that styling applied to an imported component will only affect the component itself.

Layout and Navigation in Sveltekit

As explained earlier, pages are treated as entirely standalone components. So, upon navigation, the existing component will be destroyed, and a new one will take over. However, elements or components need to be visible on every page in many applications, such as a navigation menu or footer. So instead of repeating them on every page, we can use a layout component.

To create a layout component that applies to every page on our website, create a file called src / routes / __ layout.svelte and paste the following code below inside.

1

2<nav>

3 <div class="nav-container">

4 <a href="/" class="nav-logo" title="Back to Homepage">David Adeneye</a>

5 <div class="nav-links">

6 <a href="/about" class="link">About</a>

7 <a href="/blog" class="link">Blog</a>

8 <a href="/projects" class="link">Projects</a>

9 <a href="/contact" class="link">Contact</a>

10 </div>

11 </div>

12</nav>

13

14<div class="container">

15

16 <slot></slot>

17</div>

18

19<style>

20 .container {

21 max-width: 1400px;

22 margin: 50px auto;

23 }

24</style>

This code above is our navigation menu that applies to all pages of our portfolio website. The default layout component that Sveltekit uses, if you don’t include yours, looks like this:

In addition, we can use any markup, style, and behavior of our choice; the only requirement is that the component must include a <slot> for the page content like the way we did above in the __layout.svelte file.

Routing in Sveltekit

Like every other popular SSR solution, Sveltekit has a great file-based routing system. Pages in your app are stored by default inside the src / routes folder; this means that the structure of your application is defined by the structure of your codebase, specifically the content of src / routes.

Our portfolio website contains about six pages:

  • Home – index.svelte (already created that above)
  • About – about.svelte (we would create that in this section)
  • Blog – blog.svelte (we would create that in next section)
  • Projects – projects.svelte (copy the code file in the github repo)
  • Contact – contact.svelte (copy the code file in the github repo)
  • [id].svelte – Dynamic routes (copy the code file in the github repo)

Since we have created our navigation header structure for these pages above in the src / routes / __ layout.svelte. Open the about.svelte and insert the following code below:

1

2<svelte:head>

3 <title>About</title>

4</svelte:head>

5

6<div class="main_container">

7 <section>

8 <div class="inner-container">

9 <h2 class="about-title">I'm David Adeneye👋</h2>

10 <div class="about-subtitle">

11 <p>

12 Software Engineer and a Technical Writer with a solid

13 background in Computer Science, I'm passionate about making

14 the web accessible for everyone. I design and develop visually compell ing applications with user-friendly interaction that drive business g owth and improve user experience. When I'm not solving problems,

15 I love to create technical content for engineers and tech

16 startups across the globe.

17 </p>

18 <p>

19 Creating magic daily on the internet. You can send me

20 an email at <span class="info-text">adeneyeabiodun@gmail.com</span>

21 </p>

22 </div>

23 </div>

24 </section>

25</div>

26

27<style>

28 .main_container {

29 margin: 0 80px 0 65px;

30 }

31

32 .about-title {

33 font-size: 4.2rem;

34 font-weight: bold;

35 margin-top: 11rem;

36 }

37

38 .about-subtitle {

39 margin-top: -2rem;

40 }

41

42 .about-subtitle >p {

43 width: 60%;

44 font-weight: normal;

45 font-size: 1rem;

46 line-height: 2rem;

47 }

48

49 .info-text {

50 font-style: italic;

51 font-weight: bold;

52 }

53</style>

The navigation component will always be visible, and clicking between the pages will always replace page content. Now head over to see our portfolio website in action. Your about page should look like this below.

About-Page

Open Source Session Replay

Debugging a web application in production may be challenging and time-consuming. OpenReplay is an Open-source alternative to FullStory, LogRocket and Hotjar. It allows you to monitor and replay everything your users do and shows how your app behaves for every issue. It’s like having your browser’s inspector open while looking over your user’s shoulder. OpenReplay is the only open-source alternative currently available.

OpenReplay

Happy debugging, for modern frontend teams – Start monitoring your web app for free.

Consuming REST API in Sveltekit

To learn how to fetch data from a REST API and the concept of loading in Sveltekit, we would build a demo blog post on our website. We will be interacting with a free fake REST API called JSONPlaceholder, it’s a free online REST API for testing and prototyping.

To get started, open src / routes / blog.svelte and paste the following code or read along with the accompanying source code.

1<!-- src/routes/blog.svelte -->

2<svelte:head>

3 <title>Blog</title>

4</svelte:head>

5

6<script context="module">

7 export const load = async ({ fetch }) => {

8 const res = await fetch("https://jsonplaceholder.typicode.com/posts");

9 const blogposts = await res.json();

10 return {

11 props: {

12 blogposts,

13 }

14 }

15 }

16</script>

17

18<script>

19 export let blogposts;

20</script>

21

22<div class="container">

23 <h1>My Articles</h1>

24 <div class="blogposts">

25 {#each blogposts as post}

26 <div class="post">

27 <h2>{post.title.substring(0, 20)}</h2>

28 <p>{post.body.substring(0, 80)}</p>

29 <p class="readmore">

30 <a style=" color: rgb(10, 10, 139);" href={`/blog/${post.id}`}>

31 Read More

32 </a>

33 </p>

34 </div>

35 {/each}

36 </div>

37</div>

Let’s analyze the code above. Take note of the <script context="module"> in line 6 – it is necessary because load runs before the component is rendered. The per-component instance code should be in a second <script> tag. We then use the load function to fetch our demo blogposts from the jsonplaceholder fake api to be displayed on our website.

The load function in sveltekit is similar to getStaticProps or getServerSideProps in Next.js, except that it runs on both the client and the server.

In addition, don’t forget to copy the accompanying CSS code within the code block if you’re building along with this tutorial for your page’s styling.

Your blog.svelte should look like this below:

Blog Page

Using Dynamic routes in Sveltekit

Building a blog like this, we would need dynamically generated routes. Sveltekit enables us to implement this easily through dynamic routes.

To implement this, create a new folder called blog. Dynamic parameters in Sveltekit are encoded using [bracket]. For example, create a file called [id].svelte inside your blog folder. Open the file and paste the following code or follow along with the source code.

1<script context="module">

2 export const load = async ({ page, fetch }) => {

3 const id = page.params.id;

4

5 const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);

6

7 const post = await res.json();

8

9 return {

10 props: {

11 post,

12 }

13 }

14 }

15</script>

From the code, we accessed the parameter within the load function and stored it with the variable id; the parameter was then used to fetch the exact blog post of that id. Suppose you go back to the blog.svelte you will see how we accessed the dynamically generated pages with a href in line 33 below:

1<p class="readmore">

2 <a style="color: rgb(10, 10, 139);" href={`/blog/${post.id}`}>

3 Read More

4 </a>

5</p>

You can see how we access the exact blog post with the post.id. So when you click on Read Moreit will load a new page to read the entire blog.

Deployment Sveltekit Application

In Sveltekit, before you can deploy your app, you will need to adapt it for your development target. It helps simplify your deployment process by providing several plugins known as adapters. Adapters are small plugins that take the built app as input and generate output for deployment.

Sveltekit provides a few officially-supported adapters:

Static adapter: This is an adapter for the Sveltekit app that prerenders your site as a collection of static files compatible with hosting services like Github pages and the likes.

Vercel adapter: An Adapter for Svelte apps that create a Vercel app, using a function for dynamic server rendering. It is used for deploying your app to the Vercel hosting platform.

Netlify adapter: Adapter for Svelte apps that create a Netlify app, using services functions for dynamically generating pages. It is used for deploying your app on the Netlify platform.

Let’s take a look at how to deploy our demo application to Netlify.

Deploying Sveltekit on Netlify

For you to deploy Sveltekit on Netlify, you need to use the netlify-sveltekit adapter.

Lets install the adpater into our project with the following command below:

1npm install -D @sveltejs/adapter-netlify@next

After the installation is complete, add the adapter into your project’s svelte.config.js file. Insert the following code below into the file.

1import adapter from '@sveltejs/adapter-netlify';

2

3export default {

4 kit: {

5 adapter: adapter(),

6 target: '#svelte'

7 }

8};

Then create a netlify.toml file in your project’s base directory and specify a build command and publish directory. Insert the following code below into the file.

1[build]

2 command = "npm run build"

3 publish = "build"

After all this setting, then deploy your project on Netlify with Git or the Netlify CLI.

This is the link (jolly-franklin-11e50c.netlify.app) to the final deployed website on Netlify

Conclusion

I hope you enjoyed working through this tutorial. We explored the fundamental concept of Sveltekit by building a sample portfolio website and most importantly how to consume REST API with our demo blog within the app and also how to deploy sveltekit application on Netlify. You can try to put what you have to learn to practice by building other pages or upgrade this demo to your taste if your looking to build a portfolio website for yourself.

The supporting repo for this article is available on Github.



Source link