Svelte is an exciting new JavaScript framework that offers a novel approach to building web applications.
Svelte borrows some concepts from older JavaScript frameworks like React and Vue. With prior knowledge in any of these, we can easily transition into Svelte.
This summer, a lot of Svelte’s monthly updates were focused on enhancing developer experience — DX
, performance improvements, better TypeScript
support, and some bug fixes. Let’s take a look at some of these:
await
shorthandAccording to the Svelte docs, await
blocks allow you to branch on the three possible states of a promise: pending, fulfilled, or rejected.
Consider the code below:
{#await promise} <!-- pending state --> <p>Loading...</p> {:then value} <!-- fulfilled state --> <p>The value is {value}</p> {:catch error} <!-- rejected state --> <p>An error occurred: {error.message}</p> {/await}
In the code above, we have pending, fulfilled, and rejected. The {#await}
block matches all three in the current syntax; however, when we do not need to show the loading state, there is no way to omit the initial block.
The await
shorthand syntax enables us to omit the loading state block for the promise’s resolve value.
Consider the code below:
{#await promise then value} <p>Do somthing with value{value}</p> {/await}
Similarly, we can omit the then
block as seen below:
{#await promise catch error} <p>Something went wrong: {error.message}</p> {/await}
trusted
event modifierSvelte provides different event modifiers that alter the behavior of the event. We tag these modifiers to the end of events by using the pipe character.
Consider the code below:
<script> function handleSubmit() { console.log("submitting for data"); } </script> <form on:submit|preventDefault={handleSubmit}> // do something </form>
In the code above, we modify the submit
event with the preventDefault
. Thus, we prevent the page from reloading when the form is submitted.
The isTrusted
modifier enables the event to check if the event is trusted and to trigger the handler only if the event is trusted. That is, if event.isTrusted
is true
. And an event is trusted if it is triggered by a user action:
<button on:click|trusted={() => console.log('Trusted event'); }></button>
export { ... } from
syntax in componentsThis feature aims to enhance developers’ experiences by providing a concise way to import files when working with bundler file handlers like @rollup/plugin-url and the Webpack file-loader
.
Currently, we have to do:
import dogImgJpg from './dogImgJpg.jpg'; export let dogImg = dogImgJpg;
The above pattern is a bit verbose since we have to explicitly import
and export
the file.
Syntax such as export {…} from
would throw an error since it does not include the necessary import
. However, Svelte now supports this feature in v3.41.0. So we can simply export the dogImgJpg.jpg
image above by doing:
export { default as dogImg } from './dogImgJpg.jpg';
This implicitly imports dogImgJpg
.
Similarly, this feature aims to enhance developers’ experiences by enabling us to destructure object properties and export them in a single line:
const man = {surname: 'eagles', firstname: 'lawrence'}; export let {surname} = man;
errorMode
compiler optionThis feature adds an errorMode
to the Svelte compiler options — svelte.compile()
. When errorMode
is set to warn
, Svelte will log errors as warnings and continue compilation instead of throwing an error.
This is also a part of Svelte’s work on svelte/preproccess
, which is aimed to improve the preprocessing of TypeScript files.
This alluring feature makes it possible to use Svelte inside a shadow DOM by specifying a ShadowRoot
as the target
when creating a component.
This makes it possible to take advantage of the style encapsulation of the shadow DOM, something difficult to do in Svelte because Svelte always appends styles to document.head
. You can learn more about style encapsulation and the shadow DOM here.
Svelte added a TypeScript plugin and VS Code extension.
The VS Code extension — Svelte for VS Code — uses the Svelte language server to provide IntelliSense for Svelte files in VS Code. Also, this extension comes bundled with a prettier plugin that acts as a formatter for Svelte files.
We can format our Svelte files with this formatter by adjusting our VS Code settings as seen below:
... "[svelte]": { "editor.defaultFormatter": "svelte.svelte-vscode" }, ...
Also, before installing and using this extension, it is important to note this:
CLI
by running:code –uninstall-extension JamesBirtles.svelte-vscodesvelte/ssr
package for SvelteKit ssr
SvelteKit is to Svelte what Next.js is to React. SvelteKit is a framework for building web applications of different sizes. And it provides support for routing, code-splitting, server-side rendering and offline support, and more.
With this feature, svelte
is resolved to svelte/ssr
when building for ssr
. And this enables tree shaking for lifecycle event handlers, which is a technique in JavaScript used for removing dead code and preparing our code for production.
It is important to note that in SSR mode
, all Svelte lifecycle methods — onMount
, beforeUpate
, afterUpdate
, and onDestroy
— do not do anything. Thus, they should be removed from the final bundle.
However, build tools like Rollup and Webpack cannot detect this. As a result, they end up in the generated bundle. This leaves room for further optimization of our code.
The new svelte/ssr
package is an equivalent module to svelte
, but the lifecycle methods are designed as noops
. Noops
or no-ops
can be designed in ES6
as seen below:
const noop = () => {};
By doing this, these lifecycle methods can now be removed using tree shaking by Svelte bundler plugins such as rollup-plugin-svelte
and @sveltejs/vite-plugin-svelt
. This produces a more optimized and production-ready code.
svelte-check
The latest version of svelte-check
provides the path to your tsconfig.json
or jsconfig.json
. Consequently, diagnostics would only be run on files that are referenced in that config. For example: svelte-check --tsconfig "./tsconfig.json"
.
Svelte is an awesome technology that provides a fresh take on how to build web applications.
Even though you have experience in web development with frameworks such as Vue, Angular, or React, you would still be pleasantly supersized by Svelte.
As the summer heats up, Svelte has remained cool by rolling out several interesting and alluring new features and enhancements. And if you have not yet used Svelte, now is the right time to give it a try.
You can read about more updates to Svelte in its changelog.
Install LogRocket via npm or script tag. LogRocket.init()
must be called client-side, not
server-side
$ npm i --save logrocket // Code: import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML: <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script> <script>window.LogRocket && window.LogRocket.init('app/id');</script>
Hey there, want to help make our blog better?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowLearn how to implement one-way and two-way data binding in Vue.js, using v-model and advanced techniques like defineModel for better apps.
Compare Prisma and Drizzle ORMs to learn their differences, strengths, and weaknesses for data access and migrations.
It’s easy for devs to default to JavaScript to fix every problem. Let’s use the RoLP to find simpler alternatives with HTML and CSS.
Learn how to manage memory leaks in Rust, avoid unsafe behavior, and use tools like weak references to ensure efficient programs.