Description: https://images.manning.com/360/480/resize/book/5/d3ed2a4-e017-493e-beb6-776c7e2c5cbe/Volkmann-Svelte-HI.png

From Svelte and Sapper in Action by Mark Volkmann

This article delves into the Svelte REPL.


Take 40% off Svelte and Sapper in Action by entering fccvolkmann into the discount code box at checkout at manning.com.


Svelte REPL

REPLs exist for many programming languages. A REPL reads the code you enter, evaluates it (possibly compiling and reporting errors), prints the result of the code, and loops to allow repeating this process.

Svelte provides a browser-based REPL that supports defining Svelte components, seeing their rendered output, and more. Using the REPL is the easiest way to experiment with Svelte. It allows creating Svelte applications without having to download or install anything. Your first Svelte application is a click away!

To get started, browse the Svelte main website at https://svelte.dev/. Then click “REPL” near the upper-right of the page.

Code for a “hello world” app is provided by default. Modify this code to experiment various features of Svelte.


Figure 1. REPL initial screen


Experimenting is one use of the REPL; another is creating an ever-growing collection of examples you can draw from as you learn about Svelte. You’re highly encouraged to take advantage of this feature.

Using the Svelte REPL

Initially the only file provided in the REPL is App.svelte. This file can import other files defined in additional tabs with the REPL (not separate browser tabs).

To add more .svelte or .js files, click the “+” to the right of the existing file tabs and give it a name. By default, newly created files have a .svelte extension, but this can be changed to .js by typing .js at the end of the file name.

To delete a .svelte file, hover over its tab and click the “x” that appears.

The right side of the page contains three tabs labeled “Result”, “JS Output”, and “CSS Output”.

The “Result” tab shows the rendered output of App.svelte.

The “JS output” tab shows the JavaScript generated by the Svelte compiler for the app.

When the “Result” tab is selected, the lower-right corner of the REPL shows output from calls to console methods such as console.log.

The “CSS output” tab shows the minimized CSS generated by the Svelte compiler for the app. Unused CSS selectors aren’t included. All selectors include generated CSS class names that scope the CSS to the component.

The top bar in the REPL contains links to many Svelte resources including a tutorial, the API docs, examples, the Svelte blog, the Svelte FAQ, the main page for Sapper, the Discord chat, and the Svelte GitHub repo.


Figure 2. Svelte web site header


To hide this bar in order to gain more editing room, click the “full-screen editor” icon which looks like a dashed square.


Figure 3. REPL full-screen button


After clicking, this icon changes to an “X”. To restore the top bar, click the “X”.


Figure 4. REPL exit full-screen button


Currently there’s no option in the REPL to format .svelte files. Perhaps an option to do this using Prettier will be added in the future.

Prettier is a popular tool for formatting code from many languages including JavaScript, HTML, CSS, and more. See https://prettier.io.

To reset the REPL to its starting point which is a basic “Hello World” app, click “REPL” in the header.


Figure 5. REPL reset


Your first REPL app

Let’s create a simple app and begin learning some features of Svelte.

The provided hello world app always says hello to “world”. Let’s change this to say hello to anybody. Add the following HTML before the <h1> tag:

 
 <label for="name">Name</label>
 <input id="name" value={name}>
  

The HTML element input is an example of an “empty element”. This means it can’t have child nodes. When empty elements are used in Svelte components, they don’t need to be terminated with />.

NOTE:  If Prettier is used to format the code it changes empty elements to be terminated this way. This is why some code examples in this article show terminated empty elements.

Now we can enter a name, but it doesn’t change the greeting. We need to add event handling to change the value of the name variable when the user types in the input. We can do this using an inline arrow function or a reference to a function defined in a script tag. Change the input to the following:

 
 <input
   id="name"
   on:input={event => name = event.target.value}
   value={name}
 > 
  

This works, but it’s a bit verbose. We can do better using the Svelte bind directive. One use is the bind the value of a form element to a variable. This causes the form element to display the current value of the variable. If a user changes the value of the form element, the variable updates to match.

Change the input to the following:

 
 <input id="name" bind:value={name}>
  

Oh my, this is nice! And if the variable name is value instead of name, it can be shortened to the following:

 
 <input id="name" bind:value>
  

This isn’t stylish though. Let’s add styling to change the color of the greeting. Add the following after the <script> tag and before the HTML.

 
 <style>
   h1 {
     color: red;
   }
 </style>
  

Great! Now the greeting is red.

Let’s allow the user select a color. We do this by providing a color input. This allows using the native color picker to select a color. It appears as a rectangle containing a horizontal line in the screenshot below. Clicking it opens a color picker dialog.


Figure 6. REPL app with color input


Top-level variables in the script tag of a component define the state of the component.

For example, the state of the component below includes the color and name variables.

Here is the full code for this version of App.svelte:

 
 <script>
   let color = 'red';
   let name = 'world';
 </script>
  
 <label for="name">Name</label>
 <input id="name" bind:value={name}>
  
 <label for="color">Color</label>
 <input id="color" type="color" bind:value={color}>
 <div style="background-color: {color}" class="swatch" />
  
 <h1 style="color: {color}">Hello {name}!</h1>
  
 <style>
   .swatch {
     display: inline-block;
     height: 20px;
     width: 20px;
   }
 </style>
  

Let’s allow the user toggle a checkbox to change the case of the greeting. Add the following inside the <script> tag at the bottom:

 
 let upper = false;
 $: greeting = `Hello ${name}!`;
 $: casedGreeting = upper ? greeting.toUpperCase() : greeting;
  

What does $: mean? It’s called a “reactive statement”. Reactive statements are re-executed any time the value of a variable they reference changes.

In the example code above, we want to calculate a new value for greeting any time the value of name changes. We also want to calculate a new value for casedGreeting any time the value of upper or greeting changes. This is incredibly convenient!

Now we need a way to change the value of upper when a checkbox is toggled and render the value of casedGreeting. Add the following code before the <h1> tag to render the checkbox.

 
 <label>
   <input type="checkbox" bind:checked={upper}>
   Uppercase
 </label>
  

Change the <h1> tag to the following:

 
 < h1 style="color: {color}">{casedGreeting}</h>
  

Figure 7. REPL app with uppercase checkbox


This far we implemented everything in a single .svelte file named App.svelte.

Let’s move beyond this by defining a second component.

Click the + to the right of the App.svelte tab in the REPL. Enter Clock for the name of the component.


Figure 8. REPL app with uppercase checkbox


We want this component to display the current time in hh:mm:ss format.

Start by adding only the following in Clock.svelte:

 
 <div>
   I will be a clock.
 </div>
  

Back in App.svelte, add the following inside the <script> tag at the top:

 
 import Clock from './Clock.svelte';
  

Add the following at the bottom of App.svelte:

 
 <Clock/>
  

NOTE:  The space before the slash isn’t required, but many developers, and the Prettier code formatter, prefer to include it.

We now see “I will be a clock.” at the bottom of the rendered output.


Figure 9. REPL app with “I will be a clock”


Svelte uses the export keyword to define a prop which a component accepts. In a .js file export makes a value visible outside that file, able to be imported. In a .svelte file export allows components that use this component to pass a value in. For example, in the component defined below color is a prop with a default value.

Change Clock.svelte to contain the following:

 
 < script>
   export let color = 'blue';
   let hhmmss = '';
     hhmmss = new Date().toLocaleTimeString();
   }, 1000);
 </script>
 <span style="color: {color}">{hhmmss}</span>
  

Modify App.svelte to pass a color prop to the Clock component.

 
 <Clock {color} />
  

This demonstrates a shorthand syntax which is equivalent to <Clock color={color} />.

We now have a functioning clock component.


Figure 10. REPL app with clock


This gives a taste of some of what we can do in Svelte.

If you’re familiar with other web frameworks, now is good time to pause and think about the code you write to implement what we’ve seen this far in those frameworks. Is it longer? Is it more complicated?

Part 2 goes into more depth.

If you want to learn more about the book, check it out on Manning’s liveBook platform here.