Tutorial

Getting Started with Svelte 3

Published on December 12, 2019
author

Raphael Ugwu

Getting Started with Svelte 3

Introduction

When building applications with JavaScript, high performance and penetrability will always be at the crux of the decisions made by software developers. Svelte is a high-performance component framework for imperative code.

Svelte also brings a different way of scaffolding user interfaces to the table. While React and Vue perform most of their work in the browser, Svelte runs during build time by transforming the application’s component into code that updates the DOM.

This tutorial will cover the basics of Svelte and how you can harness its features to build high performance applications.

Step 1 — Building a Svelte Application

The first thing to do when building a Svelte application is to integrate Svelte with a project scaffolding tool. This tutorial will use degit.

Navigate to your terminal and run the following command to create a new directory for your application:

  1. npx degit sveltejs/template my-svelte-app

Move into the new directory:

  1. cd my-svelte-app

If you are using NPM, install the dependencies with the following command:

  1. npm install

If you are using Yarn, install the dependencies with the following command:

  1. yarn install

Run the following command to run a local development server where you can watch your application as you build:

  1. npm run dev

This starts a server on http://localhost:5000.

Svelte project folder

There are a couple of files in the project folder that were created during the scaffolding process. This tutorial will elaborate on the files which are the crux of the application:

  • package.json: This is where the packages the project will depend on are listed. It is worth noting that unlike React and Vue, Svelte’s package.json file lists only dev dependencies and none of the regular, standard dependencies you may be used to seeing in the two aforementioned frameworks. The reason is that the framework compiles your code to Vanilla JavaScript when building for production.
  • main.js: This is the entry point for all JavaScript in your application. Components are instantiated here.
  • App.svelte: This is your application’s first component. Similar to the way Vue components are created using the .vue extension. It contains all the logic, styling, and markup needed for a component to function.
  • index.html: During development, the public folder of your application will contain an unminified version of your application’s bundle. index.html is where that bundle is executed.

Step 2 — Creating a Svelte Component

Components are a basic of every Svelte application. They are written into .svelte files, using a superset of HTML. A .svelte file has two sections:

  • <script>: This section contains all the JavaScript and logic that runs the application.
  • <style>: This contains the CSS styles for the application. markup: This contains HTML markup, it’s similar to writing JSX in React.

The block of code below is an example of what a Svelte component looks like:

<script>
  let framework = 'Svelte';
</script>

<style>
  h1 {
       color: blue;
       font-family: 'Open Sans';
       font-size: 2em;
    }
</style>

<h1>This is a {framework} Component.</h1>

Result
// This is a Svelte Component.

Step 3 — Exploring Reactive Declarations

Svelte has a feature called reactive declaration. Most times when building an application, it gets a bit big. Parts of a component’s state will need to be called from other parts and recomputed if they change. This is exactly what reactive declarations are used for. Check out the code block below:

<script>
  let car = 'Mercedes';
$: carMakeSedan = car + ' E350';
$: carMakeSuv = car + ' G500';
</script>

<p> The {car} you want is a {carMakeSedan}.</p>
<p> If you would like something more expensive, go for the {carMakeSuv}.</p>

 Result
// The Mercedes you want is a Mercedes E350.
// If you would like something more expensive, go for the Mercedes G500.

Lines three and four tells Svelte to re-run this code whenever any of the referenced values change. A value should be relative when it needs to be referenced multiple times or if other values exist that depend on it.

Step 4 — Creating and Declaring Properties

When building an application, you will eventually need to pass data from component to component (also known as parent to child component). To do that, you need to declare properties with props. Svelte accomplishes this by using the export keyword. Check out the code sample below for an example:

// Car.svelte
<script>
  export let carMake;
</script>

<p>You ordered a {carMake}</p>

Navigate to the App.svelte parent component:

// App.svelte
<script>
  import Mercedes from './Car.svelte';
  import BMW from './Car.svelte';
  import Jaguar from './Car.svelte';
</script>

<Mercedes carMake={' Mercedes'}/>
<BMW carMake={' BMW'}/>
<Jaguar carMake={' Jaguar'}/>

// You ordered a Mercedes
// You ordered a BMW
// You ordered a Jaguar

There is also an option to specify default values. In the Car.svelte example below, you can specify the default value for carMake:

//Car.svelte
<script>
  export let carMake = 'Mercedes';
</script>

<p>You ordered a {carMake}</p>

Should you then fail to instantiate the component with carMake, it will revert to the default value:

//App.svelte
<script>
  import Mercedes from './Car.svelte';
</script>

<Mercedes carMake={' Mercedes'}/>
<Mercedes />

// You ordered a Mercedes
// You ordered a Mercedes

Step 5 — Exploring Logic and Binding

One particular trait of JSX in React is its inability to contain conditional statements. Most times where such logic is needed, it is usually substituted with ternary operators or some other workaround. Svelte has the ability to conditionally render markup by wrapping it in an if block. Check out the code sample below:

<script>
  let luggage = { checkedIn: false };

  function toggle() {
    luggage.checkedIn = !luggage.checkedIn;
  }
</script>

{#if luggage.checkedIn}
  <button on:click={toggle}>
    Luggage is Checked Out
  </button>
{/if}

{#if !luggage.checkedIn}
  <button on:click={toggle}>
    Luggage is Checked In
  </button>
{if}

Button changing "check in" status when clicked

Similar to frameworks like React, data flow in Svelte is top-down. Parent components set properties on child components, but not the other way round. In Svelte, you can work around this by using the bind: value directive. Check out the code sample below:

<script>
  let framework = 'Svelte';
</script>

<input bind:value={framework}> 

<p>{framework} is awesome!</p>

With this, not only will changes to the value of framework update the value of input, but changes to input will also update framework.

Text on page being updated as user types into text box.

Conclusion

Svelte may still be in its early stages, but it shows a lot of potential and promise. This post is an introduction, so there’s still a lot more that you can accomplish using Svelte. You can learn more about Svelte by reviewing their official documentation

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Raphael Ugwu

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
1 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

In the first command, there’s a typo: is should be:

npx degit sveltejs/template my-svelte-app

svelte not svelt

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.