How it works
First, Svelte creates a Component class instance. This class stores the HTML fragment, instance variables, reactive variables, slots, used variable names, compile options, instance and module script AST, and their lexical scopes. Once all the variables are identified, the Component traverses the AST and marks the variables as referenced.
Want to know when we post new content? Sign up for our newsletter and blog alerts.
Next, it traverses the template AST and creates fragment nodes for logic blocks, element nodes for element attributes, bindings, and event-handlers, slot nodes for rendering HTML inside a component, and each-block nodes for rendering arrays. Once the template is traversed, and all the variables used in it are referenced, it determines whether the variable needs to be reactive or not.
Magic the Gathering + Svelte
To learn more about Svelte, Jordan created an example app to share with the Revelry team. Since he enjoys playing the card game Magic the Gathering(3), he built a Magic card fetcher app with Svelte(4). This app uses the Svelte search feature to search for a card that hits the wonderful Scryfall API(5) and then returns back a list of different cards that could possibly match the title of the card. After viewing the different cards, a user can select a card, see details about it, and add it to their collection.
The app uses the Svelte tools for a single page render, rendering different views conditionally, and the Svelte state to pass different saved views onto different pages. Since this is a demo, the session is stored in the browser’s memory, not hooked up to a database. Svelte made it very easy to get started building the app. The readability made it a very fun tool to learn and use.
Svelte has technical advantages, including
- The ability to create Reactive Values, computed variables that update when the underlying data is changed,
- Easy to standup new projects
- Simple data binding with the bind attribute
- Since all of the heavy lifting of the DOM is done before compile time, applications are blazing fast.
- Extremely small bundle size. Compiled files from React can be ten times the size of a Svelte file.
- Svelte supports TypeScript and SvelteKit has TypeScript support built in.
- Readability and simplicity. What would take 23 lines of code in React takes only 9 in Svelte
- Scalability for large projects
Note: This article was adapted from Jordan Este’s presentation on Svelte at Revelry’s weekly engineering team meeting.
We're building an AI-powered Product Operations Cloud, leveraging AI in almost every aspect of the software delivery lifecycle. Want to test drive it with us? Join the ProdOps party at ProdOps.ai.