close icon
daily.dev platform

Discover more from daily.dev

Personalized news feed, dev communities and search, much better than whatโ€™s out there. Maybe ;)

Start reading - Free forever
Start reading - Free forever
Continue reading >

Up and running with Snowpack and Svelte in seconds

Up and running with Snowpack and Svelte in seconds
Author
Juan F. Gonzalez
Related tags on daily.dev
toc
Table of contents
arrow-down

๐ŸŽฏ

Hello guys

In this post, we'll be talking about a way to get started making web projects with ease without needing to know about extra tools and configuring stuff.

I recently came across this setup, and building something from scratch gave me the same feeling I had back when I tried create-react-app for the first time.

You know, that feeling of "Wow, this is something fast and reaaally cool."

Now I hope you're getting excited about it cuz I already am.

Let's jump right in!

lego character jumping in

What are those names?

In case you are wondering what is Snowpack and/or Svelte, let me give you some context...

Snowpack is a build tool that allows you to create your application and see the ongoing changes faster in the development process while also providing all the excellent features you may be used to with bundling applications for the deployment process.

The already known bundlers like Webpack and Parcel have to rebundle & rebuild parts of your application every time you make a change in a file and save it.

This rebundling process takes some time depending on the framework of your choice (takes more time for Angular than it does for Vue, for instance).

The difference with Snowpack is that it serves your whole application unbundled during development. As in, every file gets built just once, and then it's cached after that.

So now that you are making changes and putting features, Snowpack rebuilds only the file that has changed and serves it instantly in the browser plus, you can also use Hot-Module Replacement (HMR) to go with it.

Once you're done making the app and want to create a production build, you can plugin your preferred bundler via a plugin (lol) and have an optimized production build ready to be deployed to the hosting service of your choice.

Here's a beautiful little image that shows what this 'Unbundled Development' thing is, taken directly from the Snowpack docs.

Bundled vs Unbundled development

So now you might be thinking, "Okay, that sounds cool and all, but how am I supposed to use this for my web apps, and if it's a bundler, does it support my existing ones?."

Well, yes, and yes. It supports many of the things we've used working with other frameworks. It comes with support out of the box for things like Typescript, JSX, CSS Modules, and you can pick a template to have support for React or Vue or Svelte, and so on.

You can use the 'Create Snowpack App' to get started with your framework of choice, and you can also take an existing app and migrate it to Snowpack easily.

Refer to the Get started section in the official docs (which are very well-written by the way).

Now for Svelte's case, it's a library much like React that cares mainly about providing the UI layer of an application without paying attention to the rest of the application's stack.

Since it goes about the visual aspect of an app, you can start using it in any project you have already created by incrementally adding some Svelte components to it and have it work like before.

But I'm not going to go too much on why choosing Svelte or how to get started building cool things with it. There's already a great post on that matter written by @nimrodkra that you can read all about here.

What are we going to build?

We'll be making a sample app to demonstrate how easy it is to get started building something from scratch.

It is a relatively simple one, but it will help illustrate some of the features we can use to make something more interesting than a usual 'to-do list.'

Here's what it will look like:

Image of the built app

Starting out

To begin, open your terminal and run this command.

`npx create-snowpack-app snowpack-svelte --template @snowpack/app-template-svelte`

You can also pass in the `--use-yarn` flag if you prefer.

It will create the directory and install all the dependencies in it and then give you a message that it initialized a git repo and will show all the available commands currently in `package.json`.

Now you can use cd inside the folder and start the dev server either with `npm start` or `yarn start`

Once you do that, you'll already be with your new site open in your default browser, and a dev server with hot reloading enabled. Boom, that was fast.

Open the folder in VSCode and start making some changes in the `App.svelte` file, save it and see the changes instantly reflected there.

Now it is time to do some coding...

Fetching the data

Now go ahead and remove all the code from the template except for the first div, and we'll be putting everything that we do inside it.

We'll change the default message string to 'Random Users' and then display it inside the template within an h1 tag.

Now here comes the fun part. We'll be fetching data from an external API and render it on our page. In Angular, we use the HttpClient, and in React, we can use the Axios library.

In this case, we're going to be using the Fetch API to call the jsonplaceholder endpoint.

So we'll create a getUsers function and fetch the data there like this:


function getUsers() {
  fetch("http://jsonplaceholder.typicode.com/users")
    .then(res => res.json())
    .then(data => console.log(data));
}

And to use this function, we'll put a button on the template to call it once it's clicked.

```jsx
<button on:click={getUsers}>Fetch Users</button>
```

Here we are using the svelte syntax for the `onclick` event and passing it the name of the function that we created.

Now, if we open the browser console tab, we can see the array of users that gets returned once we click the 'Fetch Users' button.

Rendering the data

Let's display the data on our page. For that, remember to remove the console.log and instead assign the data to our `users` variable. With that done, we can now display the data on the page instead of the console.

One way we could go about doing that is to put the `users` variable directly into the template, and that will just spit out our array of objects.

But, it would display undefined until we click the button to fetch the data from the API.

To take care of that, we're going to use the {#if} construct in Svelte to validate if we have the data available or not to be displayed. We'll do it like this.

```jsx
{#if users}
ย {JSON.stringify(users, null, 1)}
{/if}
```

Now you can see the array printed all over the screen. We'll want a better way to display this data separately for each of the users returned.

How are we going to go about that? Well iterating over the 'users' array. In React, we could use the `map` function and render all the users in a list.

Here we're going to use another Svelte construct called {#each}, and we'll render a list item for every user like this.

```jsx
{#if users}
ย <ul class="user-list">
{#each users as user}
ย  ย <li>
ย <div class="user">
<h3>{user.name}</h3>
<p>Username: {user.username} </p>
<p>Phone: {user.phone} </p>
<p>Website: https://{user.website} </p>
ย </div>
</li>
{/each}
ย </ul>
{/if}
```

If you look into the response, we get from the API. You'll notice that each user object has several properties. Here I just chose the ones shown for the sake of simplicity. You can add additional ones if you like.

Applying basic styling

Ok, that works, now let's give it some styling so that they look nicer. You can write all the CSS rules inside the `<style>` tags like this.

```CSS
.App {
text-align: center;
font-family: Verdana, Geneva, Tahoma, sans-serif;
}
.user-list {
display: flex;
flex-flow: row wrap;
justify-content: center;
list-style: none;
padding: 1rem;
}
.user-list li {
width: 45%;
padding: 0.5rem
}
.user {
padding: 4px;
border: 1px solid #ccc;
border-radius: 6px;
text-align: center;
}
```

Now that looks much better. Feel free to play around with the styles and give it some more color if you like.

We're almost done. There's something else I'd like to do just that it doesn't look like an empty page at the beginning.

What if we don't have to use the button to fetch data, but instead, we fetch it once the component is created.

In that case, we're going to use one of Svelte's lifecycle methods that are called `onMount`, and we use it like this.

```javascript
import { onMount } from 'svelte';
onMount(() => { ย 
ย getUsers();
})
```

With it, we can now remove the button, and the data will be displayed on the page once it is loaded.

And that's it! We now have a fully functioning app that fetches data from an API and displays it on a page.

We could take the `div` with the _user_ class and turn it into a component and then call it from `App.svelte` but that, as they say, is an exercise left to the reader ๐Ÿ˜›.

Also, bonus points if you take the `div` with the _App_ class and turn it into a `main` tag.

โ€

---

โ€
There you have it folks, the entire application, minus the CSS styles, is very short. (About 35 lines or so)
And it didn't take too much time to get it done 'cuz we can see the result in realtime every time we save the file.

That's it for this week's post. Thanks for reading 'till this point. Hope to see you (or read you) in the next one.


โ€

โ€

Why not level up your reading with

Stay up-to-date with the latest developer news every time you open a new tab.

Read more