In this article, we will look at how to create our first svelte application from scratch.

Install Node.js

It is important to note that Svelte requires Node.js to be installed in our system. If you do not have it installed, you can install it using the official Node.js website https://nodejs.org/en

Creating your first Svelte application

For this tutorial, I will be using the Svelte + Vite template to set up the basic project structure.

Navigate to the folder where you want your svelte project to be located and run the following command:

npm create vite@latest my-first-svelte-project -- --template svelte

This will create a folder my-first-svelte-project in your current working directory. Feel free to change it to any name you would like for your svelte project.

Before we move ahead, let’s examine what this command does for us.

Using the npm tool, command creates a Svelte project with all the necessary libraries and dependencies. Since we are using the Vite tool, we have specified vite@latest to use the latest version to create the project.

As mentioned earlier, my-first-svelte-project is the project name I have selected.

We want Vite to create a Svelte project for us, so we use the option --template svelte.

Now that we know what this command does, let’s move ahead and navigate to the project folder.

cd my-first-svelte-project

Let’s install all the packages required for the Svelte project by running the following command.

npm install

Once, the packages are installed, start the development server.

npm run dev

This will run our server on port 5173 by default. Open your web browser and visit http://localhost:5173/

Running-Your-First-Svelte-Application-1

Awesome! we now have our first Svelte application running on our machine.

You may notice there is a count message on the page. When you click it, the value increases by 1.

Running-Your-First-Svelte-Application-2

Let’s look at the code base to understand how this works.

Open the src/App.svelte file in your code editor. Here, you will find the code:

....
<h1>Vite + Svelte</h1>

  <div class="card">
    <Counter />
  </div>

The <Counter /> is the svelte component which contains the code to increment the count value. You can find the code for this component in /src/lib/Counter.svelte file.

<!-- src/lib/Counter.svelte -->
<script>
  let count = 0
  const increment = () => {
    count += 1
  }
</script>

<button on:click={increment}>
  count is {count}
</button>

Notice, that these files have .svelte extension. The above file contains Javascript and HTML code together.

The javascript code within <script> tag contains a count variable initialized to 0. We can also see a function named increment which is used for increasing the value of count.

In the HTML code, we have a button element to which an event listener is set using the on:click={increment} code. This triggers the increment function.