How to use the Svelte JavaScript framework

As 2021 nears the halfway mark, the golden age of JavaScript continues. One of the most exciting characters in the current chapter is the Svelte framework. This article gives you the basics for creating a Svelte project and using some simple UI elements.

In a distinctive departure from the current groupthink represented by React, Angular, and Vue, Svelte works on the server side to compile your application into optimized JavaScript. That means that Svelte requires a build pipeline setup. 

Although setting up a build pipeline might seem like extra work, the truth is that all real development in React, Angular, or Vue requires a build pipeline in some form anyway (like create-react-app or Webpack configuration). Plus setting up the Svelte environment quickly gets you things like hot-deploy dev mode.

Svelte setup

Let’s jump right in and set up a simple build environment. You are going to use npx and degit for the purposes of creating a starter template. Use the steps in Listing 1.

Listing 1. Initial template

npx degit sveltejs/template infoworld-svelte
cd infoworld-svelte
npm install
npm run dev

At this point the starter app will be running at localhost:5000; check it out in your browser. Open the /infoworld-svelte folder in your code editor or IDE. There are two source files of interest in the /src directory: App.svelte and main.js. These two work together to define what you see in the browser.

Note: All of the code is avaiable in this repo.

Copyright © 2021 IDG Communications, Inc.

Source link