Intro to Svelte
Basic Info for Using Svelte
Updated: 03 September 2023
Introduction to Svelte
It’s a compiler.
Creating a new Project
To create a new project you can make use of degit
which will allow you to create a project from a template. You can run this with npx
:
Then simply cd
into your project directory and install dev-dependencies
You can then run the application with:
And view the application on your browser on http://localhost:5000
The project consists of the following:
package.json
for dependencies and scriptspublic
for where any code that needs to go directly to the build output will livesrc
folder contains the primary code files
In the src/main.js
file there is an import which imports the App
component and it states that the App
component should be rendered into document.body
with the props: { name: 'world }
main.js
App.svelte
In the above component the js
and css
are scoped, the {name}
is used to include expressions that we want to be evaluated
Create a Component
Create a new componen by simply creating a ComponentName.svelte
Card.svelte
This can then be imported and used another component as follows:
We can get a component to retrieve inputs using the export
keyword
And we can pass this in from our App
component with:
Reactive Display
If we need to create computed property values we need to prefix that with the $:
it will be automatically recalculated and updated in the template
If we would like to create some functionality that will enable a component to do some reactive stuff, or display based on the value of a specific component
Clicking the button will then toggle the loggedIn
state due to the on:click
event and the toggle
handler
You can create a component that iterates over a list of items using something like the following
We can then just import and use the same as the above elements
Input Binding
We can make use of input binding using the following method: