Meet Svelte 3, a Powerful, Even Radical JavaScript Framework


Meet Svelte 3, a Powerful, Even Radical JavaScript Framework

In this article, we’ll explore Svelte 3, a front-end JavaScript framework that takes a slightly different approach to frameworks. Whereas frameworks like React ship a large bundle of JavaScript, Svelte applications are compiled by the Svelte compiler into JavaScript that claims to be much smaller than the equivalent React code. And because the code runs through the Svelte compiler, it can also be optimized.

Svelte also takes a very different approach to managing data — no useState hooks in sight — and it’s a lot of fun to work with. Even if you’re a big fan of React or any of the other popular frameworks, Svelte is worth checking out. In this introduction, we’ll build a small example application to get a taste of what Svelte can offer. Let’s get started!

Getting Started

We’re not going to dive too much into bundling and the infrastructure of Svelte apps in this tutorial, so we’ll follow the Svelte tutorial to get an application up and running.

We’ll need to have Node and Git installed locally. Then we can run:

npx degit sveltejs/template github-repository-searcher

This will clone the Svelte template repository into the github-repository-searcher folder (the app we’re building will use the GitHub API to search for repositories) and set up all the tooling for us. I highly recommend this approach if you’re focusing on learning Svelte: it will let you dive right into the framework and not get bogged down in build configuration.

Once that command above has completed, you can cd github-repository-searcher to change to that directory, and then run npm install to install all the dependencies. Once that’s done, npm run dev will get the app up and running, using the Rollup bundler to build the application. Visiting http://localhost:5000 should present you with the Svelte Hello World page, and now we’re good to get building!

A Svelte component

Before we start building out more Svelte components, let’s take a look at the existing component that the template comes with. The first thing to note is that Svelte components are defined in a .svelte file. App.svelte (located in the src folder) is split into three parts:

<script>
  export let name;
</script>

<style>
  /* CSS removed to save space */
</style>

<main>
  <h1>Hello {name}!</h1>
  <p>
    Visit the
    <a href="https://svelte.dev/tutorial">Svelte tutorial</a>
    to learn how to build Svelte apps.
  </p>
</main>

Working with these Svelte files will be much easier if your editor understands them and can syntax highlight them correctly. Svelte provides a VS Code extension, which is what I use, but if you use a different editor I suggest searching on Google. Svelte has a good-sized community, so it’s likely that plugins exist for most popular editors.

Svelte components are split into three parts:

  1. The script tag is where all the JavaScript for the component is written.
  2. The style tag is where all the component’s CSS is defined. In a Svelte component, all CSS is scoped to that component by default, so any styles here only apply to the component, not globally.
  3. Anything else provided in the component is treated as HTML for the component to output. Svelte also provides templating logic to support conditional renders, looping over arrays, and so on.

To run our application, use npm run dev. This will run Rollup, our bundler, and also a small HTTP server that will serve our application up on port 5000.

Asking the User for a GitHub Username

The first step of our application is to ask the user to provide a GitHub username. We’ll then take this name and search GitHub for a list of repositories that the user has. Let’s update App.svelte to do just that.

First, in the script block, delete the export let name line. This is how we define props in Svelte, which work just like props in React. The export keyword here declares that this value is a prop that will be provided by the component’s parent. In our case though, our component won’t take any properties, so we can delete it. You’ll also need to then update src/main.js to remove the props: {...} code, as our App component doesn’t take any props. Once you’ve done that, main.js should look like this:

import App from './App.svelte';

const app = new App({
  target: document.body,
});

export default app;

This file contains what is effectively the entry point to your application. Think of it as equal to the ReactDOM.render, if you’re familiar with React.

Let’s update App.svelte with the HTML we want. We’ll create a simple form that asks the user for a username:

<script>
</script>

<style>
  main {
    width: 80%;
    max-width: 800px;
    margin: 20px auto;
    padding: 20px;
  }

  label {
    font-weight: bold;
  }

  input {
    width: 80%;
  }
</style>

<main>
  <form>
    <label for="username">Enter a GitHub username:</label>
    <input type="text" name="username" placeholder="jackfranklin" />
    <button type="submit">Load repositories</button>
  </form>
</main>

We won’t focus on CSS in this tutorial (I’m no designer!), but I’ve applied a small amount of CSS to make things look a little nicer. Now that we have our form, let’s look at how we hook it up with Svelte. The first thing to note is that there’s no explicit useState hook or similar; the approach Svelte takes is much closer to that of other frameworks like Vue or Angular, where you instead bind an input to a value. This is a common theme of Svelte, and shouldn’t be a surprise given one of its explicit goals is to allow developers to write less code.

Let’s declare a variable for the input:

let usernameInputField = '';

Then use Svelte’s bind:value directive in the template:

<input type="text" name="username" placeholder="jackfranklin" bind:value={usernameInputField}>

Svelte will do the rest for us: as the user types in the input, the variable usernameInputField will be updated and kept in sync.

Once the user has typed in a username, we need to listen out for when they’ve submitted the form. Svelte uses the following syntax to bind event listeners:

<form on:submit={onSubmit}>

This will call the onSubmit function when the user submits the form. There’s one more trick that Svelte has up its sleeve though, and that’s event modifiers:

<form on:submit|preventDefault={onSubmit}>

Now when Svelte sees a submit event on this form, it will automatically call event.preventDefault() for us. I love this: it’s one less thing for us to worry about and one more thing we can hand off to the framework.

Back in our script tag we can define this onSubmit function. It will take the username and call the GitHub API to get a list of repositories (it will return the first 30 repositories, so you’ll need to paginate if you want to get all of them, but we’ll leave that for now):

async function onSubmit() {
  const url = `https://api.github.com/users/${usernameInputField}/repos`;

  const response = await fetch(url);
  const repositories = await response.json();
  console.log('loaded repositories', repositories)
}

Once we have these repositories, we want to list them on the page and allow the user to search for a given repository. Rather than do this all in the App.svelte component, let’s create a new component called Search.svelte. It will take the list of repositories and provide an input for the user to search for the repository they’re after.

Create a new file in the existing directory called Search.svelte. I like to start my components with a small amount of boilerplate just to check I’ve got everything set up:

<script>
</script>

<style>
</style>

<p>Search component</p>

Then when I render this component on the page, I’ll be able to tell if it’s rendering correctly.

Continue reading
Meet Svelte 3, a Powerful, Even Radical JavaScript Framework
on SitePoint.

Source: SitePoint

Leave a Reply

Your email address will not be published.


*