I have been a professional software developer for 37 years and a web developer for around 10 years. My projects have used many technologies and frameworks, including raw DOM manipulation, jQuery, Ruby, Angular 1, React, Polymer, Angular 2+, Vue, Svelte, and probably some I have forgotten.
I place a high value on developer productivity. Unnecessary complexity really works against this. While I find many things to love about Svelte and Sapper, the main driver for me is their simplicity compared to other web development approaches. I know from my experience of using other frameworks that I am far more productive when using Svelte and Sapper.
My first exposure to Svelte came from watching a talk titled “Rethinking Reactivity” by the creator of Svelte, Rich Harris. It is a very compelling talk and definitely appealed to my desire to reduce the complexity of web development. That led me to dig in further, write a long article about Svelte, give talks at user groups, and expand to giving talks at conferences. The next logical step was to write this book!
The book covers nearly every topic related to Svelte and Sapper, and some that are only tangentially related. After reading this, you should be well-poised to use these tools in your next web development project.
Many authors thank their spouses for the patience they showed during the writing process. The experience of writing this book has made clear to me the sacrifices involved. My wife Tami generously gave me lots of encouragement and time to complete this project. Thank you so much Tami for helping me to achieve the goal of finally writing a book!
Thanks to my Manning development editor, Jennifer Stout, who provided just the right amount of corrections, suggestions, encouragement, and compliments to keep me going. Seeing comments like “I love this!” mixed in with comments like “You need to explain why someone would want to do this” made the writing process so much more bearable.
Thanks to Manning technical editor Alain Couniot who continually pointed out when I wasn’t being clear or was short on providing compelling examples. He also made sure I mentioned TypeScript wherever possible. The book is much better because of his feedback!
Thanks to Manning technical reviewer Erik Vullings. He tried many things in the example code that never crossed my mind to try and suggested many improvements in the text. His thoroughness was greatly appreciated!
Thanks to Peer Reynders, a volunteer MEAP reviewer who went through all the code examples with a fine-tooth comb and pointed out many ways I could improve it.
Thanks to reviewers who added their own takes on ways to improve the book: Adail Retamal, Amit Lamba, Clive Harber, Damian Esteban, David Cabrero Souto, David Paccoud, Dennis Reil, Gerd Klevesaat, Gustavo Filipe Ramos Gomes, Jonathan Cook, Kelum Senanayake, Konstantinos Leimonis, Matteo Gildone, Potito Coluccelli, Robert Walsh, Rodney Weis, Sander Zegveld, Sergio Arbeo, and Tanya Wilke. More eyes and more opinions definitely helped!
Thanks to Charles Sharp of Object Computing, Inc. He has been the most frequent editor of all my previous writings. Charles donated large amounts of time over past 10 plus years to making me a better writer . . . Oxford comma and all!
Thanks to Eldon Ahrold of Object Computing, Inc. for reviewing the chapter on Svelte Native. Eldon is a very experienced mobile and web developer, and I’m lucky to be able to bounce ideas off of him.
Finally, thanks to Dr. Ebrahim Moshiri who hired me into Object Computing, Inc. 24 years ago. He provided me with an environment that encourages continual learning and I’ve never stopped. I most likely would not have been in a position to write this book if it wasn’t for the career he gave me.
Svelte and Sapper in Action is for web developers who want to increase their productivity. Maybe you have a nagging suspicion that there must be an easier way to develop web applications. Good news--there is, and you will learn about it here!
Through numerous code examples, you will learn how to use Svelte and Sapper to implement many common features of web applications.
The book assumes that readers have a basic familiarity with HTML, CSS, and JavaScript:
On the topic of HTML, readers should be familiar with elements like html, head, link, style, script, body, div, span, p, ol, ul, li, input, textarea, and select.
On the topic of CSS, readers should understand the syntax of CSS rules, the CSS meaning of “cascade,” basic CSS selectors (including element names, class names, ids, descendants, and children), commonly used CSS properties (including color, font-family, font-size, font-style, and font-weight), and the CSS box model (content, padding, border, and margin).
On the topic of JavaScript, readers should know about variables, strings, arrays, objects, functions, classes, Promises, destructuring, the spread operator, exports, and imports.
I am easy to find online, should you have questions about anything in the book. My hope is that by the time you make it through this book, you will be convinced that there is something special about Svelte and Sapper. These are technologies that deserve a shot at being used in your next project.
This book is divided into 4 parts containing a total of 21 chapters.
Part 1 introduces Svelte and Sapper.
Chapter 1 explains why these approaches to web development deserve your attention. It concludes with a brief introduction to Svelte Native, a comparison of Svelte to other popular web frameworks, and a description of the tools you will need to get started.
Chapter 2 walks you through building your first Svelte applications using an online tool (called the “REPL”). Apps built this way can be saved, shared with others, and exported to continue development locally. Then the steps for developing Svelte apps locally are described.
Part 2 dives deep into Svelte, providing thorough coverage along with lots of example code.
Chapter 3 teaches you how to build Svelte components. This includes the logic, markup, and styling. Then it covers managing component state, using reactive statements, and using module context. Finally, an example of developing and using a custom component is presented.
Chapter 4 covers Svelte block structures that wrap conditional logic, iteration, and promise handling around markup, which is typically HTML. Conditional logic is implemented using {#if}
, iteration is implemented using {#each},
and promise handling is implemented using {#await}.
Chapter 5 explores several options for communicating between components. These include using props, two-way binding, slots, events, and context.
Chapter 6 describes the use of stores to share state between components. There are four kinds of stores: writable, readable, derived, and custom. Then techniques for using stores with JavaScript classes and persisting store data are described.
Chapter 7 shows various approaches to interacting with the DOM in Svelte components. This includes inserting HTML, using “actions” to gain access to DOM elements, and using the tick
function to manually modify the DOM after Svelte updates it. Finally, approaches to implementing dialog boxes and drag-and-drop are presented.
Chapter 8 reviews the provided lifecycle functions that enable registering functions to be called at key points in the lifecycle of components. These include onMount, beforeUpdate, afterUpdate, and onDestroy. Finally, an approach to implementing custom lifecycle functions based on the provided lifecycle functions is presented.
Chapter 9 demonstrates three approaches to adding page routing in Svelte applications: manual routing, hash routing, and using the page.js library. A shopping app is developed to demonstrate each of these options. Another popular approach is to use Sapper. Sapper routing is discussed in chapter 16.
Chapter 10 explores the extensive support for animation that is built into Svelte. The packages svelte/animate, svelte/motion, and svelte/transition are described in detail. Two approaches to animating moving items between two lists are presented. One uses a combination of the fade
transition and the flip
animation. Another uses the crossfade
transition. Finally, the creation of custom animations and using transition events is discussed.
Chapter 11 shows several approaches to debugging issues in Svelte applications. These include using the @debug
tag, reactive statements with console
methods, and the svelte-devtools browser extension.
Chapter 12 demonstrates various approaches to testing Svelte applications. Unit tests are implemented with Jest and svelte-testing-library. End-to-end tests are implemented with Cypress. Some accessibility checking is provided by the Svelte compiler. Additional accessibility testing is performed with Lighthouse, axe, and WAVE. Finally, Storybook is used to demonstrate and manually test components.
Chapter 13 explores a few options for deploying Svelte applications. These include manual deployment to an HTTP server, using Netlify, using Vercel Now, and using Docker.
Chapter 14 covers additional topics related to Svelte. These include form validation, using CSS libraries, using “special elements,” creating Svelte component libraries, and generating web components from Svelte components.
Part 3 explores Sapper in depth. Sapper builds on Svelte to add many features.
Chapter 15 walks through building your first Sapper application. The shopping app developed in chapter 9 is recreated using Sapper.
Chapter 16 explores many aspects of Sapper. First, the default file structure of Sapper applications is explained. Then several Sapper features are described, including page routes, page layouts, preloading, prefetching, and code splitting.
Chapter 17 explores Sapper server routes. These enable implementing API services in the same project as the client side of a web app. An example of implementing create, retrieve, update, delete (CRUD) services is presented.
Chapter 18 shows how Sapper apps can be “exported” to generate static sites. This can be desirable for apps where it is possible to generate the HTML for every page at build time. An example of such an app is implemented, containing pages related to the rock/paper/scissors game, and dogs in my family.
Chapter 19 describes how Sapper apps support offline operation using a service worker. Many caching strategies are described. Details about the default Sapper service worker are provided, as are descriptions of the service worker events install
, activate
, and fetch
. An approach to enabling the use of HTTPS in the Sapper server is presented. Finally, techniques to verify the offline behavior of a Sapper app are shared.
Part 4 goes beyond Svelte and Sapper.
Chapter 20 explores preprocessing source files to add support for alternative syntaxes. Popular options include Sass, TypeScript, and Markdown. Examples of using each of these are provided.
Chapter 21 provides an introduction to Svelte Native. This combines Svelte and NativeScript to build mobile applications for Android and iOS. Two online REPL apps will get you started building Svelte Native apps without installing any software on your computer. The provided components for display, forms, actions, dialogs, layout, and navigation are described, and details about styling Svelte Native components are provided. An example app that demonstrates most of these is implemented. Finally, the NativeScript UI add-on library is described, and an example app using one of its components, RadSideDrawer
, is presented.
The learning doesn’t stop after the last chapter! The seven appendixes contain important information.
Appendix A provides links to many resources related to Svelte, Sapper, Svelte Native, and more.
Appendix B describes how to use the Fetch API to invoke REST services.
Appendix C describes the basics of using the MongoDB database, which is used in chapter 17.
Appendix D describes how to configure and use ESLint to check for issues in your Svelte and Sapper apps.
Appendix E describes how to configure and use Prettier to format the code in Svelte and Sapper apps.
Appendix F describes how to use several VS Code extensions when editing Svelte and Sapper apps with VS Code.
Appendix G describes how to use Snowpack to build Svelte applications. Snowpack implements a more efficient way to build web applications than the approach typically used by module bundlers such as Webpack, Rollup, and Parcel.
Throughout the book we’ll develop a Travel Packing application. Most chapters add features to the app based on the topics they cover.
Readers who are new to Svelte should read chapters 1 through 8 before skipping to any of the later chapters. These cover the core principles of Svelte. Readers with previous Svelte experience can skip to chapters of interest.
Much of the code in the book can be found in the author’s GitHub repositories at https:// github.com/mvolkmann. In particular, see https://github.com/mvolkmann/svelte-and-sapper-in-action and https://github.com/mvolkmann/svelte-native-components.
To run the code, you will need to install a recent version of Node.js. If you do not already have this installed, browse to https://nodejs.org/ and click either the LTS or Current button to download it.
This book contains many examples of source code both in numbered listings and in line with normal text. In both cases, source code is formatted in a fixed-width font like this
to separate it from ordinary text. Sometimes code is also in bold
to highlight code that has changed from previous steps in the chapter, such as when a new feature adds to an existing line of code.
In many cases, the original source code has been reformatted; we’ve added line breaks and reworked indentation to accommodate the available page space in the book. In rare cases, even this was not enough, and listings include line-continuation markers (➥). Additionally, comments in the source code have often been removed from the listings when the code is described in the text. Code annotations accompany many of the listings, highlighting important concepts.
Purchase of Svelte and Sapper in Action includes free access to a private web forum run by Manning Publications where you can make comments about the book, ask technical questions, and receive help from the author and from other users. To access the forum, go to https://livebook.manning.com/#!/book/svelte-and-sapper-in-action/ discussion. You can also learn more about Manning’s forums and the rules of conduct at https://livebook.manning.com/#!/discussion.
Manning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the author can take place. It is not a commitment to any specific amount of participation on the part of the author, whose contribution to the forum remains voluntary (and unpaid). We suggest you try asking the author some challenging questions lest his interest stray! The forum and the archives of previous discussions will be accessible from the publisher’s website as long as the book is in print.
Appendix A lists a large number of online resources. Most of these are directly related to Svelte and Sapper, but some cover topics applicable to all varieties of web development.
|
R. Mark Volkmann is a partner at Object Computing, Inc. (OCI) in St. Louis, where he has provided software consulting and training since 1996. As a consultant, Mark has assisted many companies with JavaScript, Node.js, Svelte, React, Vue, Angular, and more. Mark has created and taught many courses on topics including React, Vue, AngularJS, Node.js, jQuery, JavaScript, HTML5, CSS3, Ruby, Java, and XML. He is a frequent presenter at St. Louis-area user groups. He has presented at many conferences, including Nordic.js, Jfokus, NDC Oslo, Strange Loop, MidwestJS, No Fluff Just Stuff, and XML DevCon. Mark frequently writes articles on various software development topics. These can be found at https://objectcomputing.com/resources/publications/mark-volkmann. |
In his spare time, Mark likes to run. To date he has run 49 marathons in 39 states.
The figure on the cover of Svelte and Sapper in Action is captioned “femme Corfiote,” or a woman from the island of Corfu, in Greece. The illustration is taken from a collection of dress costumes from various countries by Jacques Grasset de Saint-Sauveur (1757-1810), titled Costumes de Différents Pays, published in France in 1797. Each illustration is finely drawn and colored by hand. The rich variety of Grasset de Saint-Sauveur’s collection reminds us vividly of how culturally apart the world’s towns and regions were just 200 years ago. Isolated from each other, people spoke different dialects and languages. In the streets or in the countryside, it was easy to identify where they lived and what their trade or station in life was just by their dress.
The way we dress has changed since then and the diversity by region, so rich at the time, has faded away. It is now hard to tell apart the inhabitants of different continents, let alone different towns, regions, or countries. Perhaps we have traded cultural diversity for a more varied personal life--certainly for a more varied and fast-paced technological life.
At a time when it is hard to tell one computer book from another, Manning celebrates the inventiveness and initiative of the computer business with book covers based on the rich diversity of regional life of two centuries ago, brought back to life by Grasset de Saint-Sauveur’s pictures.