Lawrence Eagles Senior full-stack developer, writer, and instructor.

What’s new in Svelte: Summer 2021

4 min read 1147

What's New in Svelte Summer 2021

Introduction

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:

New features in Svelte

1. await shorthand

According 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}

2. Adding the trusted event modifier

Svelte 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>

3. Support for export { ... } from syntax in components

This 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.

4. Object destructuring when prop is exported

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;

5. Adding an errorMode compiler option

This feature adds an errorMode to the Svelte compiler optionssvelte.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.

6. Render Svelte components inside a shadow DOM

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.

7. Introducing a new TypeScript plugin with a VS Code extension

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:

  • If you are using the old Svelte extension by James Birtles, uninstall it. You can easily do this through the CLI by running:code –uninstall-extension JamesBirtles.svelte-vscode

8. Introducing a new svelte/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.



9. Updating 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".

Conclusion

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.

Cut through the noise of traditional error reporting with

LogRocket is a digital experience analytics solution that shields you from the hundreds of false-positive errors alerts to just a few truly important items. LogRocket tells you the most impactful bugs and UX issues actually impacting users in your applications.

Then, use session replay with deep technical telemetry to see exactly what the user saw and what caused the problem, as if you were looking over their shoulder.

LogRocket automatically aggregates client side errors, JS exceptions, frontend performance metrics, and user interactions. Then LogRocket uses machine learning to tell you which problems are affecting the most users and provides the context you need to fix it.

Focus on the bugs that matter — .

Lawrence Eagles Senior full-stack developer, writer, and instructor.

Leave a Reply