- It is a free and open-source front end JavaScript framework.
- Key feature of Svelte
- It is a compiler.
- It has
no dependencies
for execution. - Does not require
Virtual DOM
as all the pre-work is done during compilation. - Svelte code is then compiled into
vanilla JavaScript
.
- It has
- Helps to create
component
based web development. - It provides as a
small bundle size
. - Relies on
Templates
instead of using extension languages likeJSX
.- It has good readability as HTML, CSS and JS are available in single
.svelte
file. - The structure of
.svelte
file is given below:<script> export let name; </script> <style> h1 { color: purple; } </style> <h1>{name}</h1>
- The
script
tag, which is an optionalJavaScript block
. - The
style
tag, which is another optional block like acommon HTML style tag
. - The
template
block, is only required block that containspresentation/view
of components.
- The
- It has good readability as HTML, CSS and JS are available in single
Reactivity
is built into the language/framework itself.- Product grade Svelte Apps can be created using legacy
Sapper
or upgradedSvelte Kit
.
- It is a compiler.
- It is created by
Rich Harris
and maintained by theSvelte core team members
. - Rich Harris created Svelte at
New York Times
.- In
2016
, he started a small project with below:- JavaScript compiler that would produce quality code
- Be light and does not abstraction of the DOM
- Super-fast loading time
- Fast performance
- In mid-November 2016, he made his first commit
- Four days later, the first beta is available
- Ten days after this beta, on
November 26, 2016
, he published a blog frameworks-without-the-framework - Three days after this blog,
Svelte v1.0.0
was born. - With a big cleanup,
v2.0.0
was released inApril 2018
- A complete overhaul
v3.0.0
was released inApril 2019
- In
- Along with Svelte; NYT it is home for creators of
BackboneJS
,UnderscoreJS
, andD3
.
- Svelte converts your app into ideal JavaScript at build time, rather than interpreting your application code at run time.
{}
are used to referJavascript variables
inside in themarkup
<script> let name = 'world'; </script> <h1>Hello {name}!</h1>
- From
Svelte v3.x
system providesA11y
- Accessibility warnings if inaccessible markups are added. - If markup attributes are having same name as variables then Svelte supports a
Shorthand attribute
notations.<img src={src} alt="A man dances."> <!-- short attribute notation --> <img {src} alt="A man dances.">
<style>
tag rules are scoped only to the component its defined and will not leak to entire page.import
statement is used to import components from other files and include in current component.{@html }
tag can be used to render HTML directly into a component. Un-trusted sources may lead to XSS attacks.<script> let string = `this string contains some <strong>HTML!!!</strong>`; </script> <p>This is text - {string}</p> <p>This is HTML - {@html string}</p>
- Reactivity:
- Heart of Svelte reactivity starts with defining
events
to updateDOM
.- Svelte enforces use of
on:
directive for declarations; exampleon:click
,on:keyup
,on:change
- Events actions can be declared in-line using ES6 arrow functions
<div on:mousemove="{e => m = { x: e.clientX, y: e.clientY }}">
- Event Dispatching:
- For example, user created a custom button [child component] and any click event of the custom button should be allowed to managed in the child component then this feature is used.
- In the child component event should be declared.
createEventDispatcher
can be used to process event on the child and then forward to parent.- Example here
- Event Forwarding:
- For example, user created a custom button [child component] and any click event of the custom button should be allowed to managed in the parent component then this feature is used.
- In the child component event should be declared
<button on:click/>
to support Event Forwarding. - Example here
- Svelte supports DOM event modification using below
<button on:click|<modifier>={handleClick}>
Modifier Summary preventDefault Calls event.preventDefault() before running the handler. stopPropagation Calls event.stopPropagation(), preventing the event reaching the next element passive Improves scrolling performance. Svelte will add it automatically where it's safe to do so nonpassive Explicitly set passive: false capture Fires the handler during the capture phase once Remove the handler after the first time it runs self only trigger handler if event.target is the element itself ()
should not be added during function call.<script> let count = 0; function handleClick() { count += 1; } </script> <button on:click={handleClick}> Clicked {count} {count === 1 ? 'time' : 'times'} </button>
- Svelte enforces use of
- By default, svelte supports
one-way data binding
formarkup attributes
- A new tag
bind
is used to convert any markup attribute binding to two-way data binding. - The tag
bind:group
is used to bind values to grouped markup attribute like Radio Buttons, Check Boxes and Dropdowns/Multi Selects. - The tag
bind:innerHTML
is used to display html text for elements with acontenteditable="true"
.
- A new tag
- Javascript variable update supports
two-way data binding
that are used inmarkup
- Svelte does not
update result variables
if anyvariables part of equation getting updated
. - A new variable definition
$:
is used to make any variable support to two-way data binding. - Variable defined using
$:
should always be on left hand side. It will updateDOM
if any variable defined on left hand side is updated. $:
notation can be used with javascript statements, blocks & if statements.- Svelte does not
update array/object variables
if anyfunctions like push, pop, split are used
.
- Svelte does not
- Heart of Svelte reactivity starts with defining
- Props:
- Properties are used to
pass data from one component to another
. export
keyword is used to declare props.- Initialization of variable is used to
default values
of props. - We can map props to object using
spread
operator if the object variables arehaving same name as props
.<!-- Info.svelte --> <script> export let name; export let version; export let speed; export let website; </script> <p> The <code>{name}</code> package is {speed} fast. Download version {version} from <a href="https://www.npmjs.com/package/{name}">npm</a> and <a href={website}>learn more here</a> </p> <!--App.svelte --> <script> import Info from './Info.svelte'; const pkg = { name: 'svelte', version: 3, speed: 'blazing', website: 'https://svelte.dev' }; </script> <!--Without Spread Operator> <Info name={pkg.name} version={pkg.version} speed={pkg.speed} website={pkg.website}/> <--> <!--With Spread Operator --> <Info {...pkg}/>
- Properties are used to
- Statements:
If/else
statements are used to conditionally display markups{#if <condition>} <markup> {:else if <condition>} <markup> {:else } <markup> {/if}
Each
statements can be used to loop an array and display markups.- It also supports descturing
each cats as { id, name }
- We can get index of current record
{#each cats as cat, i}
- If user wanted to update specific record. Each provides mechanism to identify records using key attribute
{#each things as thing (thing.id)}
- It also supports descturing
{#each <array> as <reference>} <markup with reference> {/each}
Await
statements can be used to work with promises.{#await <promise>} <p>...waiting</p> {:then value} <p>The value is {value}</p> {:catch error} <p style="color: red">{error.message}</p> {/await}
- Lifecycle:
- Every component has a lifecycle that starts when it is created, and ends when it is destroyed.
onMount
runs after the component is first rendered to the DOM.- It's recommended to put the
fetch
inonMount
rather than at<script>
because ofserver-side rendering (SSR)
- If the
onMount
callbackreturns a function
, that function will be called when the component isdestroyed
.
- It's recommended to put the
onDestroy
runs when component is destroyed.- It is used for clean-up of items like
clearInterval
- It is used for clean-up of items like
beforeUpdate
function schedules work to happen immediately before the DOM is updated.afterUpdate
runs code once the DOM is in sync with data.tick
is unlike other lifecycle functions- When component state is updated in Svelte, it doesn't update the DOM immediately.
- Instead, it waits until the next microtask to see if there are any other changes that need to be applied, including in other components.
- This avoids unnecessary work and allows the browser to batch things more effectively.
await tick()
can be used inside an async function which returns a promise that resolves as soon as any pending state changes have been applied to the DOM.
- Every component has a lifecycle that starts when it is created, and ends when it is destroyed.
- Stores:
- Data might be required to be accessed accross mulitple unrelated components. To achive this
stores
are used. - A
store
is simply an object with asubscribe method
that allows interested parties to be notified whenever the store value changes. It has below methods- Writable store initialization
const count = writable(0);
- Update
count.update(n => n + 1);
- Set
count.set(0);
- Refer Store Value
{$count}
- Javascript templating is${count}
- Readable store initialization
const time = readable(initial value, <start function that retruns stop function>);
- Derived store
const elapsed = derived(initial value, <start function>);
- Writable store initialization
- Data might be required to be accessed accross mulitple unrelated components. To achive this