Getting started with Svelte - a short tutorial

By

Get started with Svelte, the compiled JavaScript framework, by scaffolding a project with npx sv create, installing dependencies, and running npm run dev.

~~~

Since I started using Hugo as a static site generator to create websites, I’ve grown to love this approach to publishing on the web, compared to using a CMS that generated pages dynamically, as I was used to - in the past.

Svelte is a JavaScript framework that gives me the same feeling. Compared to React, Vue, Angular and other frameworks, an app built using Svelte is compiled beforehand, your site visitors don’t have to be served the framework and libraries code, and as a result all the fruition of the experience is smoother, consumes less bandwidth, and everything feels faster and lightweight.

As with Hugo, which disappears at deployment and generates plain HTML, Svelte disappears and all you get is plain JavaScript.

But let’s jump to the meat of the article. How to get started with Svelte.

You need to have Node.js installed. Check out my how to install Node.js post if you don’t have it already!

And make sure it’s the latest version (how to update Node.js).

Node installs the npx command, which is a handy way to run Node commands. Scaffold a new app with the official Svelte CLI (sv):

npx sv create firstapp

(The old npx degit sveltejs/template + Rollup template path is outdated. Use sv create now.)

The CLI asks a few questions: template, TypeScript, and tooling. Pick what you want, then go into the firstapp folder and install dependencies:

cd firstapp
npm install

We’re now ready to run our Svelte site in development mode, by running

npm run dev

This starts the app on localhost (the CLI prints the URL; older screenshots used port 5000):

CLI

If you point your browser there, you’ll see the “Hello world!” example:

Browser

You’re now ready to open the code in your favorite editor. The src folder contains all you need to tweak the app. The entry file wires up the root component, which lives in App.svelte, a single file component. The mental model looks like this:

<script>
export let name;
</script>

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

<h1>Hello {name}!</h1>

If you are familiar with Vue.js, it’s a similar concept. You define the markup, the style and the JavaScript for each component in a single .svelte file.

Tagged: Svelte · All topics

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about svelte: