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.

The post What’s new in Svelte: Summer 2021 appeared first on LogRocket Blog.

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

What’s new in Svelte: Summer 2021

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.