Developing Web Components with Svelte Building a Library of Reusable UI Components — Second Edition — Alex Libby
Developing Web Components with Svelte Building a Library of Reusable UI Components Second Edition Alex Libby
Developing Web Components with Svelte: Building a Library of Reusable UI Components, Second Edition ISBN-13 (pbk): 979-8-8688-1179-1 ISBN-13 (electronic): 979-8-8688-1180-7 https://doi.org/10.1007/979-8-8688-1180-7 Copyright © 2025 by Alex Libby This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director, Apress Media LLC: Welmoed Spahr Acquisitions Editor: James Robinson-Prior Development Editor: James Markham Coordinating Editor: Gryffin Winkler Cover designed by eStudioCalamar Cover image by Freepik.com Distributed to the book trade worldwide by Apress Media, LLC, 1 New York Plaza, New York, NY 10004, U.S.A. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail booktranslations@springernature.com; for reprint, paperback, or audio rights, please e-mail bookpermissions@springernature.com. Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web page at http://www.apress.com/bulk-sales. Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub (https://github.com/Apress). For more detailed information, please visit https://www.apress.com/gp/services/source-code. If disposing of this product, please recycle the paper Alex Libby Belper, Derbyshire, UK
This is dedicated to my family, with thanks for their love and support while writing this book.
(This page has no text content)
(This page has no text content)
(This page has no text content)
(This page has no text content)
(This page has no text content)
(This page has no text content)
(This page has no text content)
xiii About the Author Alex Libby is a front-end engineer and seasoned book author who hails from England. His passion for all things open source dates back to the days of his degree studies, where he first came across web development and has been hooked ever since. His daily work involves extensive use of React, Node.js, JavaScript, HTML, and CSS. Alex enjoys tinkering with different open source libraries to see how they work. He has spent a stint maintaining the jQuery Tools library and enjoys writing about open source technologies, principally for front-end UI development.
xv About the Technical Reviewer Vadim Atamanenko is an experienced software engineer with over 25 years of experience, a senior member of the IEEE and Harvard Square associations, and an active participant in the scientific community. He is the author of numerous scientific articles, an expert in international hackathons, a lecturer in software development courses, and currently serves as the Head of the Development Department at Freedom Life Insurance Company. Vadim also shares his knowledge and expertise through more than 40 articles published in online publications in two languages (English and Russian). He is always open to meeting new people and exchanging knowledge.
xvii Acknowledgments Writing a book can be a long but rewarding process; it is not possible to complete it without the help of other people. I would like to offer a huge vote of thanks to my editors, in particular, Nirmal Selvaraj and James Robinson-Prior; my thanks also to Vadim Atamanenko as my technical reviewer, James Markham for his help during the process, and others at Apress for getting this book into print. All have made writing this book a painless and enjoyable process, even with the edits! My thanks also to my family for being understanding and supporting me while writing. I frequently spend a lot of late nights writing alone or pass up times when I should be with them, so their words of encouragement and support have been a real help in getting past those bumps in the road and producing the finished book that you now hold in your hands.
xix Introduction Developing Web Components with Svelte, Second Edition is for people who want to learn how to quickly create web components that are efficient and fast using the upcoming Svelte framework and associated tools. This project-oriented book simplifies the setting up of a Svelte web component library as a starting point before beginning to explore the benefits of using Svelte to create components not only usable in this framework but equally reusable in others such as React, Vue, and Angular. We can use this as a basis for developing an offer that we can customize to our needs, across multiple frameworks. It will equip you with a starting toolset that you can use to create future component libraries, incorporate the processes into your workflow, and that will allow you to take your components to the next level. Throughout this book, I’ll take you on a journey through creating the base library, before adding a variety of components such as a select box, tabs, and the typical tooltip components. We will also touch on subjects such as writing documentation, testing components, and deploying into production – showing you how easy it is to develop simple components that we can augment later quickly. With the minimum of fuss and plenty of practical exercises, we’ll focus on topics such as building the functionality, styling, testing in a self-contained environment, and more – right through to producing the final result viewable from any browser! Developing Web Components with Svelte, Second Edition uses nothing more than standard JavaScript, CSS, and HTML, three of the most powerful tools available for developers: you can enhance, extend, and configure your components as requirements dictate. With Svelte, the art of possible is only limited by the extent of your imagination and the power of JavaScript, HTML, and Node.js.
xxi Changes in This Edition Below are some of the changes made for this edition of Developing Web Components with Svelte: • Updated Storybook to version 8 • Updated Svelte to version 4 • Refactored all Storybook stories to use a newer format, switching from default Svelte to JavaScript • Fixed issues in the RadioButton component • Included a new section on accessibility • Included a new Animation chapter and components: Alarm, Switch, and ProgressBar • Updated installation of Svelte project to use Vite as a replacement: this bypasses workarounds used when creating the original library project • Refreshed color scheme to new shade and named library GarnetUI (to avoid confusion) • Added coverage testing • Added a new Avatar component as conversion from React to Svelte • Updated documentation to use a new format as part of the update to Storybook 8
xxii • Switched to using Vitest from Svelte Testing Library • Removed the SideBar component (as this didn’t work well in Storybook) • Added a new Switch component Changes in This ediTion
1© Alex Libby 2025 A. Libby, Developing Web Components with Svelte, https://doi.org/10.1007/979-8-8688-1180-7_1 CHAPTER 1 Getting Started Let’s suppose for a moment that you’ve spent any time developing with frameworks such as React. In that case, I’m sure you will have come across the principle of creating web components. We can drop these self-contained, reusable packages of code into any number of projects, with only minor tweaks needed to configure the package for use in your project. Sound familiar? What if you found yourself creating multiple components and were beginning to reuse them across multiple projects? We could use them individually, but that wouldn’t be the most effective way – instead, why not create a component library? Creating such a library opens some real possibilities – we could build our library around standard components that everyone uses or focus on a select few that follow a theme, such as forms. At this point, you’re probably assuming that we’d do something in React, right? Wrong. Anyone who knows me knows that I like to keep things simple – while there is nothing technically wrong with React (it’s a great framework), I want to do something different. We will build such a component library for this book, but the framework I’ve elected to use is a relatively new kid on the block – Svelte. It, however, won’t just be another library, but one based around web components! Why, I hear you ask?
2 There are many reasons for doing this, but performance is the most important one – Svelte’s architecture is different from most frameworks, making it superfast than many of its rivals and one that suits web component architecture perfectly. It means we can create something in Svelte (easy to pick up) and use it in React, Angular, Vue, and so on. Any framework that uses JavaScript (and potentially npm packages) can effectively use this library. Throughout this book, we’ll explore how to write web components using Svelte, bring them together in a unified library, and explore the steps required to release them to the world at large with minimal effort. In time-honored tradition, we must start somewhere – there’s no better place than to start with a look at what we will create through this book, set some boundaries, and get some of the tools and resources ready for use. Let’s first answer this question before we do so (and get anyone up to speed who hasn’t used web components). What Are Web Components? To answer this question, we must go back ten years to the Fronteers Conference in 2011, where web components were first introduced to developers. There are many ways to describe what a web component is, but I like the definition given by Riccardo Canella in his article on the Medium website, where he states that …Web components are a set of web platform APIs that allow you to create new custom, reusable, encapsulated HTML tags to use in web pages and web apps. Chapter 1 GettinG Started
3 This definition is just a tiny part of what they are – in addition, it’s essential to know that they • Are based on web standards and will work across modern browsers • Can be used with any JavaScript-based framework Wow – that’s powerful stuff! Gone are the days when we had to use a React component in a React-based site or, likewise, for Angular. Just imagine: we could build a component in Svelte and then use it in different frameworks – as long as they are based on JavaScript. There is one question, though, that I bet some of you are asking: Why choose Svelte? It’s a valid question, as Svelte is not as well known as other frameworks such as React. However, there are three reasons for choosing this framework: • It’s a fair bet that many of you use React in some capacity; we could develop a web component in React, but we would be missing out on one key factor: interoperability. We need to build the component using a different framework, such as Svelte. • Svelte’s architecture pushes compilation into the build process, preventing the need for a runtime library when operating in a browser (unlike its competitors such as React). It means the end code is superfast – it doesn’t have the overhead of that library, plus compiled code is as close as you will get to pure HTML, CSS, and JavaScript. Chapter 1 GettinG Started
Loading comments...
Reply to Comment
Edit Comment