In this article, we will look at how to create our first svelte component. We will begin by creating a basic project structure using the Svelte + Vite template.

Let’s run the below command to create the project folder.

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

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

Next, navigate to the project folder and 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/

The root component of the application is found in App.svelte file under the src directory. This file contains the default code. For demonstration, I will clear the content of App.svelte and write the code from scratch.

Open the App.svelte file and include the below code.

<script>
  let message = "Hello World";
</script>

<h1>{message}</h1>

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

For now, this code simply contains a variable message which is displayed using the h1 element.

Let’s create a new component called RandomNumber which will display a button. When this button is clicked, it will display a random number. Let’s create a new file called RandomNumber.svelte in the src directory which will hold our code.

<!-- src/RandomNumber.svelte -->
<script>
  let randomNumber = 0;
  const generateRandom = () => {
    randomNumber = Math.floor(Math.random() * 1000 + 1);
  };
</script>

<button on:click={generateRandom}>
  Random Number : {randomNumber}
</button>

Within the <script> tag, we have declared a reactive variable randomNumber and initialized its value to 0. Next, we have declared a function generateRandom which will assign a random number between 1 to 1000.

The HTML code contains a button with on:click directive which calls the generateRandom on the click event of the button.

Let’s import RandomNumber component in the App.svelte file.

<!-- src/App.svelte -->
<script>
  import RandomNumber from "./RandomNumber.svelte";

  let message = "Hello World";
</script>

<h1>{message}</h1>
<RandomNumber />

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

Creating-Your-First-Svelte-Component-1

On clicking the button, you can observe random numbers being displayed.

SCreating-Your-First-Svelte-Component-2

We have successfully created our first component in Svelte!