Installation, Components, Properties and DOM events in a nutshell
Hi rocks, Sasha here. In this article we are going to see some core mechanics of Svelte, so you can easily start making your own webapp with this almost perfect UI library.
Let's start with setup. Open your terminal, go to the folder you want to create project and execute the next commands:
npx svelte3-app
npm run dev
This will create a standard "Hello World" project configured with rollup. The project's structure is pretty standard. The entry point is in
src/main.js
. It only renders App.svelte on body and passes name prop to it.Unfortunately, you have to add .svelte at every import, but you can fix it easily by updating rollup.config.js: go to
resolve
object and add:extensions: [".svelte"]
As you see, a Svelte component incorporates all the necessary inside a single .svelte file. The basic structure is:
<script>
// all js code here
</script>
<!-- HTML code here -->
<style>
/* all css here */
/* css is scoped by default */
</style>
Let's create our first component. Name it as you like (with .svelte extension, I called it Page.svelte) and write the above code in there. Import it in App.svelte and put it in your template. At this point, your App.svelte must look like this:
<script>
import Page from "./Page";
</script>
<main>
<Page />
</main>
I removed style section from it as we don't need it.
The cool thing is that although Page is an empty component, it won't crash your app. It is very useful when you are prototyping the structure of your application, without implementing it yet. You just use this empty components as placeholders, and then put the content you need inside them.
In order to expose a variable as property you just have to export it as in normal javascript. Let's export a variable named
number
from our Page and display it:<script>
export let number;
</script>
<h1>{number}</h1>
<style>
/* all css here */
/* css is scoped by default */
</style>
Props in Svelte are set the same way you do in other libraries: add it as attribute in template:
<Page number="5" />
Now, this component will display
5
.The last thing we are going to do in this tutorial is to update
Page
by adding a button to increase value in App
. Steps are:let value = 0
);number={value}
);<button on:click{increaseValue}>Increase</button>
);Your App.svelte should look like this:
<script>
import Page from "./Page";
let value = 0;
const increaseValue = () => {
value ++;
}
</script>
<main>
<Page number={value} />
<button on:click={increaseValue}>Increase</button>
</main>
The only new thing here is:
on:click={increaseValue}
. I think you can figure it out by your self 😉. In Svelte, you can listen to any DOM event using on:<event_name>={<listener>}
In the next tutorial, we are going to create a classic Guess a Number game. It will be a bit more complex as we are going to use custom events to communicate with parents and learn some lifecycle hooks.
External links: