Vanishing frameworks

Vanishing frameworks


Why do we use frameworks? Angular, React and Vue help us build complex web applications: structure the code, manage the state, and develop complex interfaces. Over the past decade, frameworks have become the standard. Expensive standard. Since frameworks have come into use, JS has greatly swelled. Pages weighing a few megabytes becomes larger, and a substantial part of this volume is the framework itself. It seems to be a little bit, but for the user it is critical - the page may not even load on the phone or on the weak internet. This is a problem.



In addition to overweight, classical frameworks have many other disadvantages and they are not suitable for all projects. These problems are solved in the “endangered frameworks”. What is this new trend, why is it not “another JS framework”, but a good idea and how mysterious frameworks can improve our applications, Pavel Malyshev will tell.

About Speaker: Pavel Malyshev ( PaulMaly ) - fullstack with experience more 10 years. Works in the company Mustlab, which is engaged in outsourcing the web, smart TV and mobile devices, as well as IoT. Evangelist Svelte JS in Russia leads Telegram group on this topic.



What should not be in the report


When I was thinking about this story, I decided that it should be non-standard. Therefore, I wrote out what should not be here. There will be no emphasis on a specific framework, comparisons with other frameworks - they are all fed up, and, of course, I do not want to be a Captain Obvious. All this should not have been in my story, but, unfortunately, it will be ...

When you read the name, you probably thought that there was another framework, and there is already a zoo of them.



It seems to me that if a new framework appears, then the old ones do not satisfy some of our needs. Perhaps the needs themselves change over time, and that is why we need new solutions - more effective and interesting. Therefore, I ask you to approach the above from an unbiased point of view and look at the disappearing frameworks as a new tool that may help in your work.

First, let's figure out who is who.

Who is who


I took the big three and Svelte. Interestingly, each tool characterizes itself differently. Angular positions itself as a framework for all occasions, "everything in a box." React mimics the library: “I'm as small as a library,” but with the entire infrastructure, this is also a full-fledged framework. Vue is a supposedly progressive framework. You can jump to it from jQuery by sequentially transferring code, starting almost from the usual script tag without collectors. Svelte is a magically fading framework. WAT?

Let's figure out what I'm talking about.

Why did frameworks disappear?


We send too much code to our users.

Our customers are becoming more mobile, but Internet technologies are not always good - even 3G is not everywhere, not to mention LTE. We need to reduce the size of the code.

On this subject there is interesting research from 2017, which shows that if there are a lot of JS in your application, then you can put only 130 Kb so that the user is satisfied . If JS is small, then up to 170Kb.This difference is due to the fact that the study took into account that JS is different from other types of resources, it must be parsed, interpreted, etc. .



In the study, 130 Kb is not only JS, but everything, including CSS, HTML, of course, without images. At the same time, one Angular weighs 143 Kb, and we have not even written a single line of code yet. Let's see what the current solutions offer us.

Performance


In principle, any classic framework is an abstraction over the platform, which allows us to write at more convenient levels. This is bad because any abstraction carries some costs, including in terms of performance.

We incur additional costs due to unnecessary abstractions between our code and the browser.

The trick of the endangered frameworks is that they remove unnecessary abstractions and calculations from the browser runtime , making analysis and calculations at the time of compilation. That is why they disappear. Let's talk about this in more detail below.

Compatibility


Solutions that are written for a classic framework cannot be applied anywhere.

They work only within the framework of this framework. For example, you do 2-3 projects on your favorite React, wrote a bunch of cool solutions for it, and then decided to move to Angular. These solutions you no longer need, they can throw. Although the basic idea is to match the components, classical frameworks make it impossible for us to reuse the code.

The trick of the endangered frameworks is that they have no abstractions , and in this case there is no framework in runtime. Your code is absolutely vanilla JS, which can be carried anywhere - in any project, even on another framework. For example, you can take the code on the disappearing framework and transfer it to React.

Code splitting & amp; tree shaking


Old technologies make it difficult to apply new technologies.

Most of the frameworks were created when these technologies were not so developed. We have a fairly monolithic core, and any component, even the smallest piece of your code, is tied to the whole framework. Accordingly, it is not possible to effectively do code splitting and even tree shaking.

Now all the frameworks are developing in the direction of greater modularity in order to "shake" better. In the endangered frameworks, this is decided out of the box, because they are made so that only the code that you initially need is added to the bundle, and it solves your problem exclusively. This is a very specific case - as if you wrote the code for your task with your hands and stuck it in a bundle, only the framework does it for you.

Feature cost


Any framework has the price of a new feature.

The community requires different new features and each member has something different, and every feature has its price. In the endangered frameworks, this problem is solved at the concept level, because any feature that you do not use will never get into your bundle.
So, the main question: can endangered frameworks, and specifically Svelte, solve all these problems? Let's figure it out.

ba s from runtime


Rantaym is a rather ephemeral topic. It is not entirely clear what it is, and different people understand it differently. In this context, I will speak about runtime from the point of view of two aspects: the environment in which the code is executed and directly code execution .

Runtime as an environment


We will understand by example.If the code is written in Vanilla, then the only runtime that is needed is the DOM. If the code is written in React, then another runtime is needed: DOM, React and React DOM.

Any, the smallest component of your code in React will depend on the environment in which your framework runs, that is, runtime.


Runtime as code execution


The second point is runtime in terms of code execution during operation. Consider today's frontend runtime base case — a virtual DOM — a large piece of runtime, for example, in React applications — with a simple example:

  & lt; h1 & gt; Hello {world} & lt;/h1 & gt;  

In this piece of HTML there is a dynamic variable. In terms of virtual DOM, the code works like this.

  • This variable is changed.
  • Builds a virtual DOM tree in memory.
  • Compares with previous version.
  • DOM manipulations are performed directly, which are pretty effective in the end, because we got a certain diff and know exactly where to change in a real DOM.



The
Virtual DOM is an absolute overhead, because it will always be faster like this: as soon as changes occurred, immediately made changes to the DOM.



Question: how to understand what has changed and what needs to be changed? A virtual DOM solves the issue of what has changed, not the speed of these changes. The speed is achieved due to the fact that we know as well as possible what has changed and can effectively manipulate the DOM.

Compile it


To resolve this issue, the disappearing frameworks simply determine the changes at the compilation stage: you wrote the code; at compile time, the disappearing framework builds all the dependencies, calculates what manipulations in the DOM are needed. In fact, everything that a virtual DOM does in runtime, a vanishing framework does in build time: it generates direct manipulations from the DOM, which are simply called during runtime. The result is a scheme: when we make changes, the DOM is immediately manipulated.

You can’t write a question without a wall of complexity. But a compiler can do it for you.
Rich Harris, creator of Svelte

I'll tell you how I met Svelte. We had an interesting project - a widget for pasting on an unlimited number of sites, and we don’t know what sites it is, on what devices the user will open them. The widget should be very small in size and very fast in speed. Naturally, when we took on this task, we immediately understood what to do on React or even on Vue is not an option, because it turns out a lot of extra overhead.

We were almost inclined to write on Vanilla, but it is difficult and not always convenient to maintain. But we were lucky - we stumbled upon Svelte. The basic idea of ​​this framework is given in the quotation: you cannot write a serious application on Vanilla, because you will very quickly run into a wall of complexity - the team will have difficulty in working, there are no common approaches, and the compiler can do it for you.

How it works




Source code is a framework-based code - a code that depends on the framework. Everything is as usual: there is some documentation, you write code, as if you are using any other framework that has some kind of API, principles and approaches. Everything is as usual.

At build time, this code is compiled.As a result, vanilla JS is in the bundle, and, as I said, exactly the code that is needed for the execution of your particular application gets there. If you add another new function there in two minutes or use a new feature from the framework, Svelte will add it there, and it will also fall into the bundle. Otherwise this will not happen.

Consider the stages in more detail. The first step is component . Consider the same component.

  & lt; h1 & gt; Hello {world} & lt;/h1 & gt;  

In the second step - AST - the code is generated into an abstract syntax tree.

  {"type": "Element", "name":
 "h1", "children": [{
 "type": "Text", "data":
 "Hello", ....}]}
  

The third step is the DOM API . Based on the tree, the code is generated directly, which is necessary for the operation of this component. The code is very simple, there are no complicated runtimes and abstractions in principle.

  function update (changed, ctx) {
  if (changed.name) {
  text_1.data = ctx.name;
  }
 }
  

At the end of the article, indicate in the survey if you like the idea of ​​AOT-compiling the Svelte framework? last time the majority expressed a positive opinion.



Now let's see what Svelte is.

Svelte


The English word svelte, or svelt, means "slim, flexible." Svelte JS is this!

I argue that this is not the “Yet another JS framework” because it is a build-time UI framework . Normal frameworks run in runtime, and Svelte exists only before we compile it.

This compile-time static analyzer , or a static code analyzer that runs through the code during compilation, analyzes it statically and generates a corresponding final bundle based on this.

This ahead-of-time compiler is the AOT compiler that does all this.

The creator of the Rich Harris framework, which you can know from tools like Rollup, Ractive, Buble - an analogue of Babel - is a cool guy. In my opinion, the same Rollup is still the best implementation of tree-shaking. In it, he appeared much earlier than in the Webpack, and still works better. Harris initially did the Svelte framework, including tree-shaking, code splitting, and other modern approaches.

Svelte is a tool to write vanilla JS without having to write to vanilla JS.

Let's take a look at this framework from the inside.

Single File Component


Svelte is a single-file component . If you worked with Vue, it will remind you very much of this framework, but this is no accident. The syntax, which is primarily used in Vue, is borrowed from the Ractive framework, which Harris also did back in 2012. This framework, unfortunately, did not become popular, it seems to me, because it came out to 1.0 too late. They are so muddied with the versions that Ractive was in minor versions for 6 years.

Many Vue interfaces were borrowed from there, and Svelte is a follower of Ractive. Therefore, it will seem that everything is similar, but single-file components appeared in Ractive in 2013. They look a little different, but in general - it seems. Any component you write on Svelte will look something like this.

  & lt; h1 & gt; Hello {world}! & lt;/h1 & gt;
 & lt; script & gt;
  export default {
/* component behavior */
  };
 & lt;/script & gt;
 & lt; style & gt;
/* scoped styles */
  & lt;/style & gt;  

Above is some HTML template - plain HTML with no exceptions. The only thing is that there is a certain template language on top of it, which is called HTMLx . I will tell you more about him later.

Next comes the script in which we write the behavior of our component. How to write it is described in the guide. There you can import, make different functions and methods - all as in Vue.

You can use the scoped style to get isolated component styles out of the box. It works like this: in a main compilation, a hash is generated, the result is a Shadow DOM emulation, as it were.

None of the sections are required, so a component can consist of only one HTML.

HTMLx Syntax


As with any HTML, data is written in brackets.

  & lt; button & gt; Say hello {name} & lt;/button & gt;  

This is how conditional statements are written.

  {# if name}
  & lt; button & gt; Say hello {name} & lt;/button & gt;
 {/if}  

Enumerations and cycles:
  {# each users as {name, email}}
  {#if name}
  & lt; button & gt; Say hello {name} & lt;/button & gt;
  {/if}
 {/each}  

You can use directives to catch events, for double-binding data.

  {# each users as {name, email}}
  {#if name}
  & lt; button on: click = "say (name)" & gt; Say hello {name} & lt; button & gt;
  {/if}
 {/each}  

There are very few directives in HTMLx - only 4-5 types, and there are no custom directives like in Angular.

You can put any dynamic data into any attributes, there is no problem with that.

  & lt; div id = "{dynamic}" class = "used" & gt;
 {#each users as {name, email}}
  {#if name}
  & lt; button on: click = "say (name)" & gt; Say hello {name} & lt; button & gt;
  {/if}
 {/each}
 & lt;/div & gt;  

Isolated styles and deleting unused


If you use insulated styles, then besides the fact that they are isolated, unused styles are still cut out automatically.

  & lt; div id = "{dynamic}" class = "used" & gt;
 {#each users as {name, email}}
  {#if name}
  & lt; button on: click = "say (name)" & gt; Say hello {name} & lt; button & gt;
  {/if}
 {/each}
 & lt;/div & gt;
 & lt;/style & gt;
  .used {...}
  .unused {...}
 & lt;/style & gt;  

If the used style, then it is used, and if the unused style, it will not be in the bundle. The framework will cut everything, but neatly. Therefore, this feature can be easily broken if you use a lot of dynamics. Svelte will think: "I would rather not touch" - and leave. We must be careful, but it is very convenient. Since there is a static analyzer in Svelte, it shows in the console at startup which styles are not used. If you really do not need them, you can immediately remove them.

Component Composition


Everything is as usual here: import the file, register it in the components, use it as a tag.

  & lt; Nested foo = "static" bar = {dynamic} bind: baz = baz/& gt;
 & lt; script & gt;
  import Nested from ‘Nested.html’; ’
  export default {
  components: {Nested}
  };
 & lt;/script & gt;  

It is possible to transfer any data through attributes, to use double binding. Or not to use - double binding is not necessary, it can even be disabled at the compiler level, and it will not be found anywhere at all. This is for those who do not like bindings. Binding is obtained using the bind: directive.

Svelte Advanced Features


The first two options are: SSR & amp; Hydration is server-side rendering and hydration, and built-in state management is built-in global state management based on its own solution, the so-called store.

In principle, you can use Redux, which many do: those who are used to Redux use it with Svelte. But there is an easier internal solution that is deeply integrated so that if you register it in the store, then it is immediately available in all component hierarchies - no manipulation at all is necessary.The only thing to use it is to use the prefix $ , that is, all the methods or data of the store are written with this prefix. $ name can be used in any template.

The store has an interesting feature that I have not seen anywhere else - it extends globally to a single hierarchy of components. If you, for example, have a Root component, it is used throughout this hierarchy. If you have another store somewhere inside this hierarchy, then this store is already distributed to the entire lower hierarchy.

This is useful when you want to make a large complex component with many subcomponents, and continue to use it in different projects, some of which have Redux, and others do not. If you are using a regular store with Redux, then you should make sure that there is Redux in the project where you add it. There is no need to do this - Svelte implements its own store for this sub-hierarchy. It can be easily transferred even to those projects where there is no global store at all. You have carried it, but Svelte has already done everything within itself.

Custom elements are supported out of the box . There is a special site that supports support with Web Components standard frameworks. According to tests, Svelte has 100% support for custom elements. It works like this: the tag name is specified, the “customElement: true” flag is set in the compiler, and a ready-to-use custom element is generated that supports all existing Svelte features.

Sapper - Svelte app maker . This is an analogue of Next.js and Nuxt.js for Vue. In principle, everything is the same: isomorphism, support for code-splitting, prefetching and offline out of the box and other features. In my opinion, recently even part of the routing ideas came from Sapper to Next.js.

But not one Svelte does it. We are for fair competition!

Who else?


Stencil is a framework from Ionic developers. They are also working on a compiled framework, but with a big emphasis on web components and custom elements. Svelte differs from it in that its components are usually compiled into regular JS classes and there is no bias in web components.

Glimmer - I think everyone knows this project. It is here only because it compiles too: it has its own bytecode, its own virtual machine, which obviously gives additional optimizations for the final code.

Marko from eBay . Not studied in detail, but they also compile, not sure that as deep as Svelte. True, I did not understand in detail and could be wrong.

Angular . There is an AOT compiler here, and it will be promoted well, but it’s just a matter of recompiling string patterns into a ready-made, broken form. As far as I understand, there is no complete AoT compilation there yet.

Hello movies


I wrote a small application - a list of movies with filters based on TMDb API. It has categories: popular, top rated, upcoming. You can walk around the pages, select a country, apply filters for it, change the language. This primitive application takes only 6.4 Kb.

In total, HELLO MOVIES is only 172 lines of code along with HTML, of which 36 lines of JS code, along with all sorts of quotes. This is all the code that I wrote in person. Naturally, all this is compiled into a much larger volume, but for me, as a developer, it does not matter.

Some more indicators. "TodoList MVC" on Svelte takes 3.6 Kb - it depends on who writes, but even on Vanilla it takes 11 Kb, and on Vue and React, and even more - 80 and 300 Kb, respectively. Project “RealWorld”, Medium clone, with registration, accounts, likes, shares, friends - 40 Kb, for React and Angular at 211 and 575 Kb. Clone “HackerNews” on Svelte - 30 Kb, on React and Vue - several times more.

Benchmarks


We all love to talk about benchmarks.I used the famous benchmark Krausest . You, probably, think that I will now show the results, where Svelte just tears everyone to shreds, and Inferno just cries to the side. But this will not happen.



I took the comparison of Svelte with the big three - Angular, React and Vue in the latest versions. As a result, he singled out the first two positions relative to Vanilla. And here the numbers are not as important as the basic idea, which is that Svelte is very balanced .

Svelte strives to be balanced - it is good in all indicators in any benchmark . In some respects, Svelte even overtakes Vanilla, in some it occupies the first, and somewhere Vue and Angular overtakes it. At the same time, in all Angular and Vue tests a lot of memory is consumed, but Svelte does not. It does not aspire to be the best at all everywhere, although it is relatively fast, consumes little memory and has a quick start. The main point is the balance.

So far, few people use Svelte - this is a fairly new tool. Let's see where it applies.

Chik-chik - and in production!


Author Svelte works for the New York Times. This is quite a big production. Of course, not the whole site is made on Svelte, I think this is a big legacy project with CMS, where everything is done primarily for editors. Many interactive special projects and widgets that they put on the page are made on this framework.



For example, an interactive survey widget about “Games of Thrones "- with animated films, with Drag & amp; Drop. This widget is implemented just on Svelte, and there are many such examples.

Japanese cloud platform for games Soft-Gear with a fairly complex admin that I have seen screenshots, on svelte. I know this because its developer is sitting in our Telegram chat room and we communicate with him.

The multicast service interface airca.st is completely made on Svelte. The storytelling service editor Dabble is completely on Svelte. A fun electric bike search service nearby i-want-to-ride-an-electric-citi with cool maps and animations also uses Svelte.

In conclusion, another of our case. Probably everyone knows RuTube. We have now made it an update for Smart TV for Tizen platforms, including Samsung. Their new app for Tizen for Smart TV will also be written on Svelte. It is already preparing for publication, it will look something like this.



Total Pros



The final standalone vanilla javascript code without dependencies . It solves only the problems that you solve in your components, there is no overhead.

Small size and high performance . There are no abstractions between code and DOM in Svelte. There is generally a minimum of abstractions.

Low entry threshold . Everyone says that it is very easy to learn Vue, but it is even easier to learn Svelte. It has a simple guide , an excellent REPL , all Links from the guide go to a ready-made example that can be poked and modified.

The power of static analysis and compilation out of the box . Although I believe that there is still a lot of work there - and the compiler is not perfect, and the static analyzer is far from being used to its fullest. But this is all wired up at the concept level, so it will evolve.

Code-splitting & amp; tree-shaking . Again, at the concept level, problems with code-splitting and tree-shaking are solved. All components and any hierarchy of components can be assembled separately. These will be separate independent modules that can be combined in any sequence and receive different packages.

Micro-frontends ready . This is very good for micro frontends. We even have a little experience, when on every page that was sent from the server using plain PHP, there was a completely independent Svelte application. despite the fact that the common code base was unified. We simply recruited from different components, for each page were collected separately and received completely independent applications. Even inside these applications, code-splitting and tree-shaking can be carried out independently.

Total Cons



Svelte is quite young, few ready-made solutions . The first releases were at the end of 2016. But there is already a second version, and even discussions are underway on the third.
Untested Approach . In principle, the approach with recompiling everything and everything is not yet fully tested in large projects. But we have been using it for a year and a half in production. Of course, there are problems, but no more than in other frameworks that we used before, in the same Vue.

No corporate support . If React supports Facebook, Angular - Google, Vue who just doesn’t support, here the project is supported by Rich Harris and the team of maintainers who work with him and I’m glad to be part of this team.

Just a week later on Frontend Conf as part of RHS ++ Pavel Malyshev goes further and tells what to do if you want more vanilla. And 33 more excellent reports on the frontend will be at the festival. Read here for more on topics and concepts and have time to join a large company of professionals at RHS ++ 27 and May 28th.

Source text: Vanishing frameworks