Chapter 1: Meet Svelte

When developers think of JavaScript frameworks, the options abound. Even within the narrow scope of front-end development that we're covering in this book, most developers will be familiar with (or have at least heard of) tools such as Angular, React, and Vue.

However, you picked up this book because you've heard of Svelte, and you've heard of it's growing in popularity. You've probably also heard that Svelte is different, and that there's something magical about it. I'm using the word magical on purpose: in fact, the original tagline for the Svelte project was "the magical disappearing UI framework."

This book is about the Svelte 3 front-end JavaScript framework, the last version as of the time of writing, which was released in April 2019.

You can use Svelte to build single, reusable components for projects of any kind, including larger applications written with Angular, React, Vue, or any other frameworks. Or, you can build entire web applications with it – just like we'll be doing in this book.

Among all the various frameworks, in most comparisons, Svelte 3 stands out for its ability to produce smaller code bundles that run faster in the browser, compared to Angular or React. This is a big part of what makes Svelte magical. But, perhaps even more importantly, developers largely enjoy working with Svelte 3; building components and applications with it feels to many very similar to using "vanilla JavaScript."

Throughout this book, I'll help you build your first, fully functional project with Svelte 3: a journaling app. We'll go from bootstrapping the development environment all the way to production with an automated continuous integration and delivery pipeline.

While building this sample app, we'll cover the majority of the features of Svelte 3. By the end, you should have a strong foundation to go and create your own apps with Svelte.

In this chapter, we'll cover the following topics:

  • Modern web app development
  • Why you should use Svelte
  • Details on the app we'll be building

Modern web app development

Before we dig deep into Svelte, or any other JavaScript framework for front-end development, it helps to take a quick trip down memory lane and look at how we arrived at modern web app development, and the role that frameworks play.

How the web became static…again

When I built my first website, in 1999, it was just like what you would expect: rich in flashy GIFs, scrolling texts, and eye-hurtlingly bright colors. It was also served by static hosts that were essentially the Italian equivalent of GeoCities.

I had built that website using the most advanced tools available for webmasters at the time: WYSIWYG editors (which stands for What You See Is What You Get): for me, that meant Microsoft FrontPage.

FrontPage worked just like Wix.com and other similar services of present day, where you build your website visually and the code is generated for you. It differed in that it was a native desktop app and, in the middle of the first browser war, it outputted code that ignored web standards and was optimized for Internet Explorer. Of course, all those websites were fully static. (In case you're wondering, I eventually "graduated" to Macromedia Dreamweaver, which was more standards-compliant; Macromedia was later acquired by Adobe, and Adobe Dreamweaver is still maintained today.)

Ten years later, in 2009, I was still building websites, but then I was making them dynamic, with server-side generation in PHP. Those were the days of "rich internet apps," where users could interact with a website, and "web 2.0," centered around collaboration and user-generated content.

Generating web pages on a server was not a novel concept per se: Java EE was released in 1999, Microsoft created ASP in 1996, and the original PHP came out in 1994! However, it was only in the second half of the '00s that those technologies became more accessible to small teams and individual developers, first of all thanks to new, simpler frameworks: for example, Django and Rails were both released in 2005. Additionally, in those years, we started seeing increasingly cheaper options for hosting web applications that require server-side rendering, especially with PHP.

Around the same time, interactivity started to appear in frontends too.

Developers had been building apps that run within browsers for a long time, leveraging plugins such as Java Applets, ActiveX objects, or Macromedia Flash (later, Adobe). Those were plagued with issues ranging from poor performance to serious security flaws, and they always ran almost completely isolated from the rest of the web page and the DOM. JavaScript was mostly considered a tool for designers to add small bits of interactivity to web pages and other gimmicks – just like its creators had originally meant it for.

Then, Google released Gmail in 2004 and the next year, they built Google Maps, and those were among the first large-scale applications to run primarily within the browser itself (any browser) without plugins. They popularized a new way of building web apps, where data is loaded dynamically in response to user action: this technology was then called Asynchronous JavaScript and XML (AJAX). The foundation for AJAX was the XMLHttpRequest API, which existed in Internet Explorer as an ActiveX object and was later implemented by other browsers in a compatible way too.

Another relevant change for JavaScript developers at the time was the creation of libraries such as Prototype in 2005 and jQuery the next year. At a time when browsers were still running JavaScript based on the ECMAScript 3 standard, these libraries provided great help by offering convenient features to web developers, such as easier ways to access and manipulate the DOM. They also helped by abstracting away the complexity of targeting all web browsers, including the then-dominant Internet Explorer 6 and its poor support for web standards.

With the help of AJAX and libraries such as jQuery, it became clear to developers that apps could run within a browser itself, and the amount and sophistication of web apps started growing.

Fast forward to 2020, and browser-based web apps are the new norm, to the point where we can often replace native, desktop apps with web ones running inside the client: from spreadsheets, to photo editing tools, to complex 3D video games.

The last decade brought along a set of innovations that helped make front-end development simpler, more accessible, and more powerful.

This included innovations in browsers, with faster JavaScript engines, and in the standards themselves. New HTML5 and CSS3 specifications added a bunch of new features, including the <video> tag that killed Adobe Flash for good, the last standing of the plugins. As for JavaScript, ECMAScript 2015 (ES2015, often called ES6) was finally released in 2015, after a much-troubled process (which is an interesting story in itself). Innovation is continuing, with technologies such as WebAssembly posed to completely rethink the way we build apps too.

As for the developer experience, a new class of front-end frameworks started to appear with AngularJS 1.0 being released in 2010, whose goal was to make it easier to write large-scale apps in JavaScript, avoiding the creation of unmaintainable "spaghetti code." We'll look a bit deeper at these frameworks and how they work, and how they compare to Svelte, later in this chapter.

Eventually, in what could be called a clear example of Nietzschean eternal recurrence applied to software development, we're back to building web apps that are completely static, and they have never been more powerful. (We're also using a very large number of GIFs once again, but at least we're doing it ironically this time!)

Building apps with the JAMstack

Along with advancements in the web technology and browsers, developers have been able to leverage new paradigms.

One of the most relevant to us in this book is the so-called JAMstack, an acronym of the following:

  • JavaScript
  • (Reusable) APIs
  • (Pre-rendered) Markup

Inside the JAMstack

The JavaScript part shouldn't come too much as a surprise: in the JAMstack, apps are written in JavaScript and run within a web browser. You can interpret this more broadly to refer to all apps that run within a JavaScript VM in a browser, to extend the definition to also include apps that use WebAssembly.

More interesting is the APIs part. One of the most sought-after features of JAMstack apps is how they deliver a great end user experience by allowing interactivity. This is possible thanks to apps interacting with other back-end services through a set of predefined APIs:

Figure 1.1 - A conceptual diagram for a JAMstack application

Figure 1.1 - A conceptual diagram for a JAMstack application

The most commonly used APIs are RESTful endpoints that are accessed via HTTP(S), just like we'll be using in this book's sample app. More recently, developers have started to leverage GraphQL too as an alternative format, which is especially optimized for data that can be represented by graphs (GraphQL was invented by Facebook, as a matter of fact). Alternative transport protocols are possible too in certain scenarios, such as using WebSocket for two-way data streaming, or protocol buffers and gRPC for apps that need to transfer large amounts of structured data (although gRPC doesn't yet work natively within web browsers and requires a proxy).

Lastly, pre-rendered markup refers to how JAMstack apps are made of bundles of HTML, JavaScript, and CSS files, as well as assets (images, fonts, and so on) that are rendered at "build-time." Using tools such as Webpack, various source files are packaged together and minified. Text content can also be pre-rendered from Markdown documents, thanks to static site generators such as Gatsby, Hugo, and Jekyll.

JAMstack apps are "compiled" and packaged inside the developers' machines or, more commonly, in a continuous integration server. The final bundle, which contains only HTML, JavaScript, and CSS files, in addition to any static asset, is self-contained, and is often deployed to object storage services in the cloud, such as Azure Blob Storage and AWS S3. Because the applications' files are completely static, developers usually place a Content Delivery Network (CDN) in front of the object storage service: this caches the files in edge nodes around the world, delivering faster speeds and lower latencies to all visitors worldwide.

Benefits of JAMstack applications

JAMstack apps are enjoying well-deserved popularity, both with developers and end users.

For teams building and operating apps, the benefits of the JAMstack mainly fall into two categories: simpler operations and better developer experience.

The latter group enjoys a great user experience, being able to use apps that are interactive and yet run within a web browser. But, most importantly, JAMstack apps feel fast.

For operators

On one hand, operations are simpler and cheaper than for traditional web applications:

  • Because JAMstack apps are just a bundle of static files, they can be deployed to object storage services on the cloud, which offer high availability and reliability, and are shockingly inexpensive: their billing model normally charges a few cents per GB stored per month. This is in addition only to the egress bandwidth cost, which you would be charged for regardless of the way the application is built.
  • When deploying the application to object storage services, there's no need to maintain a complex infrastructure: teams don't need to deal with things such as containers and container orchestrators such as Kubernetes. There are also no servers to maintain, nor operating systems and application frameworks to patch.
  • Because the apps maintain no state, replication, including geo-redundancy, involves just copying the file bundles to the separate locations and using a bare-bones load balancer.
  • JAMstack apps can be deployed atomically by copying the new bundle of "compiled" files in a staging directory, and pointing the application to the new location, with minimum downtime.
  • Lastly, as mentioned previously, apps can be cached by CDNs completely and effectively, offering faster speeds and lower latencies to your end users.

As a nice side benefit, serving your application's front-end and all static assets (scripts, images, and so on) from an object storage service and a CDN reduces the load on your infrastructure, which receives requests only for the data.

For developers

On the other hand, JAMstack apps come with a delightful Developer Experience (DX) too.

You might have noticed a similarity between the way JAMstack apps are designed and mobile or desktop ones. In both cases, the application is self-contained and runs entirely within the client, and it communicates with back-end services over the network:

  • The first consequence of this is that there's a clear separation of roles and responsibilities. As long as they agree on a common set of APIs, front-end and back-end teams can work autonomously from each other. Both teams also have more freedom in their choices around technologies and stacks, not having to depend on both parties to agree on monolithic frameworks and their templating systems.
  • The decoupling of the front-end from the back-end creates the by-product of reusable APIs that can be leveraged by other teams for their purposes, independently. For example, your organization might decide to build a native mobile or desktop app using the same back-end services, while another team could integrate the same APIs in a completely different product, and business users might even build custom interfaces, such as reporting using "no-code" solutions interacting with the same back-end.
  • Even the life cycle of the various tiers of the application is decoupled. The front-end team can change their code and redeploy the application without impacting the back-end systems.
  • JAMstack apps are normally "compiled" really fast, so developers can see their code's behavior in real time, often with Hot Module Reload (HMR) support too. The tools required to build and deploy applications are fairly standardized by now, so there are pre-made templates for most continuous integration and continuous delivery platforms.
  • Lastly, because the front-end is fully independent from the back-end, frontend developers have the ability to experiment freely. Developers can A/B test various versions of their front-end code independently and safely. In many cases, notwithstanding policies saying otherwise, they might also able to point development front-end apps to production back-end services, with no risk to the availability of the live application.

For end users

As an end user of web applications yourself, this paragraph might be familiar to you.

JAMstack apps feel, and often are, fast. When users perceive your app to be fast, their satisfaction increases, and they are easier to retain.

This is made possible by having a separation between the application code and data, by doing most requests asynchronously and by caching data extensively:

  • When requesting a JAMstack app, clients first load the app's shell, which consists of the app's code without any data. Because the app's bundle is fully static, this request can easily be served by CDNs: these have plenty of bandwidth and edge nodes in hundreds of places around the world. Users can fetch the app's shell faster, and the reduced distance to the CDN's edge node leads to less latency, which means that they start receiving data sooner. Additionally, browsers can store the app's shell in their own cache, so returning visitors might be able to avoid requesting it completely.

    Even though your app's shell might be many kilobytes in size, thanks to the improved performance of the CDN and the extensive caching, the experience for end users is a positive one.

  • Asynchronous loading of the data improves the perceived speed of your application. With JAMstack apps, browsers render the shell first, and then request the data asynchronously. Even as they wait for the data to load, users can see your app's interface and interact with it, making your app feel faster overall. This is in contrast with traditional apps, where browsers need to wait for the full HTML, both structure and content, before they can render the page and accept interactions.
  • Because your server doesn't have to render full-blown HTML pages, page generation time is faster. But even more importantly, the amount of data transferred to users is smaller.
  • Even more, by loading data asynchronously, apps can prioritize the content they're loading. For example, you could request and render the content for your app's main view before populating the sidebar.

Compared with desktop and mobile applications, JAMstack apps are delivered via a web browser using the Software-as-a-Service (SaaS) model, with constant updates, fixes, and new features, to the delight of your users.

Third-party APIs

I mentioned that the API part of the JAMstack is the most interesting one: in my opinion, this is where the biggest opportunities are.

In fact, as apps' tiers become more decoupled, you might even be able to build JAMstack apps that do not integrate with any back-end services that you (or your organization) manage.

Identity services

Perhaps the best example of this is authentication, where your app can integrate with external identity providers. There are multiple reasons why I consider this a good idea rather than rolling out your own identity system, starting from the obvious: that you have less code to manage – especially code that is usually outside your core business logic – to the fact that larger, more robust identity services can offer significant security benefits.

If you're building an enterprise application, it's likely that your organization's identities are already synchronized with Azure Active Directory (Azure AD) (for organizations that use Microsoft 365) or G Suite, both of which can be used by third-party applications too.

For consumer apps, using a social identity is often a convenient choice: Apple, Facebook, GitHub, and so on.

There are also other services, such as Auth0, Okta, and Azure AD B2C, that offer flexible, powerful options, including support for built-in accounts (users can sign up and create a new profile for your app) as well as integration with external services.

SaaS services

Aside from authentication, you can integrate with a very large number of APIs offered by SaaS providers.

For enterprise applications, you can get a vast amount of data by integrating with your organization's productivity suite, such as Microsoft 365 or G Suite. For example, you can access your users' calendars, store data inside their cloud storage space (OneDrive for Business or Google Drive), send and receive emails, create and share presentations and spreadsheets, make phone calls, and much more.

Consumer apps can leverage services such as Dropbox, Google Drive, or Microsoft OneDrive to store arbitrary, persistent data.

Besides that, you can find APIs online for literally anything, from showing maps to providing directions, from searching for images to collecting payments, and from tracking parcels to getting the status of a flight.

APIs for developers and integrations

In this far-from-exhaustive list of APIs, there are two more sub-categories of services that you could leverage in your JAMstack apps.

The first one is about APIs specifically meant for developers looking at integrating features in their applications. Examples of real API services include the following:

  • Creating a thumbnail for an image
  • Video encoding
  • Converting files into other formats, such as creating PDFs from a Word document, or converting PNG images into JPG
  • Detecting fraudulent activities
  • Stopping bots – for example, with CAPTCHAs
  • Triggering a software release with a continuous delivery pipeline
  • …and many more!

The other group is about using "low-code" or "no-code" platforms to perform certain automated tasks for your application. Services in this category include Microsoft Power Automate, Azure Logic Apps, and Zapier.

These even allow connecting to resources (such as databases, ERP systems, and so on) that cannot otherwise be safely accessed by a front-end only app or performing actions automatically in response to events; for example, sending an email notification every time you receive a new tweet or recording an entry in a spreadsheet when someone presses a button in your web app.

In the consumer space, IFTTT offers a large amount of integrations, including social networks, weather forecasts, smart home appliances (for example, lightbulbs, thermostats, refrigerators, and so on), personal fitness solutions, and other consumer platforms and services.

Why use external APIs?

The most obvious reason why you might want to integrate external APIs is that you don't have to manage them. It becomes someone else's responsibility to ensure that they're available and scale, to apply security fixes, and so on.

Another benefit might be around compliance. For example, using an external payment platform, such as Stripe or Square, frees developers from having to build applications and infrastructures that comply with PCI-DSS. If your app doesn't store any user data, you might also have an easier time adhering to privacy regulations, such as GDPR, because the burden of compliance falls on the API service providers. (But confirm this with your legal team.)

JAMstack versus SPAs and PWAs

At this point, you might be wondering how the JAMstack compares with other trends in web app development, namely Single-Page Applications (SPAs) and Progressive Web Apps (PWAs).

SPAs are web applications where all the views are contained in a single HTML page, and routing happens inside the browser. This is in contrast to multi-page applications, where each view has its own HTML page, and clients navigate between views by requesting a different page from the server.

PWAs are web applications that have three features: they use HTTPS, have a manifest file that makes them "installable" in a client, and leverage the service workers APIs in the browser to cache data and provide an offline-enabled experience to your users.

All of these three kinds of apps (single- and multi-page apps and PWAs) can be built with the JAMstack, as long as they fit the definition. That means having the requirements of being built with JavaScript (J), interacting with reusable APIs (A), and using pre-rendered markup (M). In other words, they're JAMstack apps if they can be exported as static files and don't require server-side generation.

Important note

The demo app we're building is a SPA. However, you can use Svelte 3 to build any kind of app, including multi-page apps and PWAs.

Additionally, Svelte 3 can be used to pre-render content in a server-side application, so it could be used to build non-JAMstack apps. We will not cover such an advanced scenario in this book.

Why Svelte?

To understand what's special about Svelte, we need to look at how it differs from other popular libraries and frameworks, such as Angular, React, and Vue.

Svelte versus the other frameworks

Svelte's goal is to help developers write less code, letting them build components using familiar HTML, CSS, and JavaScript. Just like React ones, Svelte apps are truly reactive, so you do not need to manipulate the DOM directly (as you would if you were using jQuery, for example): the view is automatically updated on every change in the state.

However, Svelte's main intuition, and its biggest difference from all the other popular JavaScript frameworks, is that it moves most of the processing to a compilation stage. That is, rather than relying on large and complex libraries loaded at run time, Svelte is built around a compiler that processes your application's code before emitting a small, fast, and optimized code bundle.

Another major difference from other popular frameworks is that Svelte requires almost no boilerplate code: Svelte components are written with HTML, CSS, and JavaScript blocks. Scripts feel very close to "vanilla JavaScript," while markup is defined using standard HTML tags. Svelte does not introduce new JavaScript syntax either, unlike React's JSX.

Thanks to being pre-compiled, Svelte apps have a minimal overhead, both in terms of bundled code size and performance. Smaller bundles make your pages load faster, especially for users with slower internet connections. Additionally, by performing the bulk of the work in the compilation stage, Svelte does not need to include techniques such as the virtual DOM used by React and Vue: state changes in Svelte apps are reflected directly in the DOM, without extra overhead.

In a sense, Svelte is a response to the explosion of the size of web pages. According to the HTTP Archive reports (https://www.httparchive.org/reports/state-of-the-web?start=2015_03_01&end=latest&view=list), the median size of a web page was 1,280 KB in 2015, and that has grown to 2,080 KB in 2020. Large web pages take longer to load, increasing the likelihood of users leaving your site. But they also disproportionally impact users in rural areas, where internet bandwidth is more limited.

While the requirement for compiling your JavaScript code might sound off-putting, Svelte does that in a very transparent way, by working directly within bundlers such as Webpack and Rollup. In that sense, it's not much different from other tasks that JavaScript developers perform habitually, such as transpiling to an older ECMAScript version with Babel, or converting type-safe TypeScript code into executable JavaScript. The compilation stage for Svelte is really fast, adding an unnoticeable amount of work to a normal bundling pipeline.

The Svelte project

Svelte is an open source project, whose source code is available on GitHub and was released under a permissive MIT license.

Relevant links:

Official website: https://svelte.dev/ Project page on GitHub: https://github.com/sveltejs/svelte

Compared with the likes of Angular and React, Svelte is a relatively recent framework. It was originally created in 2016 by Rich Harris (https://github.com/Rich-Harris), a software developer and visual journalist.

Svelte was first noticed by the broader JavaScript developer community in the summer of 2018, when Harris presented it in a talk at JSConf EU. This was the first time I'd heard of it myself, with an introduction to version 2.

The release of version 3 in April 2019 marked an important moment for Svelte (this is still the most recent branch as of the time of writing), as it was a complete rewrite that introduced a new, simpler syntax for writing Svelte components. With Svelte's third release also came a real uptick in the adoption of the framework.

Today, Svelte is maintained by an active community that is organized around the project's GitHub repository, and builds new releases with bug fixes and new features regularly.

It is also used by hundreds of organizations around the world, including The New York Times (where Harris is employed), 1Password, Rakuten, Philips, and GoDaddy. A list of users is maintained on the project's website.

As for developers' preferences, the 2019 State of JavaScript report (https://2019.stateofjs.com/front-end-frameworks/) portrays Svelte as well-positioned:

  • 88% satisfaction among developers; that makes Svelte the second most popular framework behind React (with 89% satisfaction).
  • Svelte ranked first among developers' interest, at 67%.
  • However, Svelte's relatively young age made 2019 the first time it appeared in the State of JavaScript report, and a quarter of respondents stated they had never heard of it.
  • Nevertheless, a fifth of Svelte users reported working in a company with over 1,000 employees (the same as React), indicating how the framework has gained momentum in more mature organizations too.

Building a journaling app

Throughout the following chapters of this book, we'll build a proof-of-concept application using Svelte 3 – a journaling app:

Figure 1.2 – Screenshot of the completed app

Figure 1.2 – Screenshot of the completed app

App features

This app features three main views:

  • The starter view is a list of all the journal entries for a given day; a date picker lets users select the day.
  • Users can add new content using a form that lets them type it in freely.
  • Content is presented to users when they select a journal entry, rendering the input text as Markdown.

The app requires authentication before users can read or write any journal entries, and it uses OAuth 2.0/OpenID Connect to achieve that.

Data is stored inside a back-end service, which runs separately from our application (remember that we're building a JAMstack app!), and our front-end communicates with the back-end service via RESTful APIs.

While this proof-of-concept app has simplified, limited functionality, it does help us learn all the core capabilities of Svelte 3 (and a few other things too). The concepts we'll be exploring are applicable both to internal, line-of-business applications, as well as external-facing ones.

The back-end service

In order to keep this book focused on front-end development using Svelte 3, we'll be using a pre-built back-end service that provides persistent storage for the data, as well as identity and access control.

To make your life simple and to let you focus on the front-end, I've built a small service that provides the required endpoints. This is written in Go and is available on GitHub at PacktPublishing/Svelte-3-Up-and-Running or https://bit.ly/sveltebook. You can download the pre-compiled binary for Windows, macOS, and Linux, and launch it on your laptop (usually by double-clicking on the executable) to instantly have the required APIs available for your front-end app to interact with.

Besides being a cheap workaround to the complexity of requiring you to build a back-end, this approach reflects the way modern web applications are built. As the developer working on the front-end portion of your app, you will need to interact with a service using predefined APIs that are maintained by a different team.

You might not have knowledge of how the back-end service works (and, truthfully, you might not want to either), and the service might be written in a completely different stack, just like this back-end app is written in Go. As we saw in the previous sections, in fact, many JAMstack applications interact with services that are maintained by completely different organizations within the company, or even different companies.

Important note

The source code for the back-end service, written in Go, is available on GitHub for you to look at and modify as you please.

The service includes common RESTful endpoints to store, retrieve, and search objects (journal entries).

It also features a mock OAuth 2.0/OpenID Connect implementation to provide identity services. This was built from scratch, but it includes just the bare minimum features to support the needs of the sample front-end application.

While the back-end service is functional, because its purpose is just to aid the development of the front-end application in this book, it is full of sub-optimal practices. In short, do not use this app or any of its code in production as is. This is especially key for the access management part, which is likely unsafe for any real-world applications; instead, you should rely on your organization's directory or, if building a consumer-facing app, on trustworthy identity service providers.

Summary

In this first chapter, we learned about the Svelte 3 framework and what makes it magical compared to other alternatives for front-end development.

We also did a retrospection on modern web app development, looking at concepts such as JAMstack apps and their benefits to developers and end users.

Lastly, we looked at a description of the application we'll be building throughout this book, which is a journaling app running entirely within the web browser and developed with the Svelte 3 framework.

In the next chapter, we'll start getting our hands dirty and begin building the sample app. We'll begin by setting up all the required tools and scaffolding for our project. At the end, we'll be ready to run a "hello world" app with Svelte 3.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.59.163