When will the JavaScript frameworks disappear?

https://medium.freecodecamp.org/do-we-still-need-javascript-frameworks-42576735949b
  • Transfer
The author of the material, the translation of which we are publishing today, a web developer, says that he is trying to regularly review the set of tools he uses. He does this in order to understand whether he can do without some of them, solving his usual problems. He recently decided to conduct an experiment and create a complex front-end application without using JavaScript frameworks.

What is a framework?


If you try to define the JavaScript framework without going into details, it turns out that this is a tool that you can use to develop complex web applications, in particular, single page applications (SPA).

In the old days, such applications were created relying on the capabilities of pure JavaScript and the jQuery library. But, with the increasing complexity of front-end applications, appropriate tools began to appear that make life easier for programmers. For example - it is React, Angular and Vue.

The frameworks that are popular these days have some similarities in common. So, the majority of front-end frameworks and libraries, relatively speaking, from Vue to React, give the developer some combination of the following features:

  • Synchronization of the state and visual presentation of the application.
  • Routing
  • Template system.
  • Recyclable components.

Are frameworks necessary for a modern developer?


The answer to the question in the heading of this section depends on how to relate to the idea of ​​the “necessity” of frameworks. I'm sure many can say that front-end frameworks are not necessary in the web developer's toolkit, and never were necessary. Although it is indisputable that these are very useful tools.

As a matter of fact, our question can be reformulated as follows: “Are the frameworks something of a“ modern jQuery library ”? Is it possible to solve the problems they are solving, by other means, for example, those that appeared at the programmers' disposal during the development of browser-based APIs?


jQuery

In fact, this question is not easy to answer, but it can be said that the development of JavaScript, technologies for working with web components and tools for assembling projects made the development of the SPA without the use of frameworks easier than ever.

In order to explore this idea, I developed a one-page application using only JavaScript, standard web components, and the Parcel bundler. In the process of work, I encountered some problems and difficulties, looking at which you clearly begin to see the strengths of modern JS frameworks.

At the same time, as soon as I coped with the initial obstacles, I was surprised at how easy it is to create a one-page application in pure JavaScript.

Experiment Application Overview


The application in question is pretty simple. It is an electronic collection of recipes and allows the user to create, view and edit recipes. The user, in addition, can mark recipes, indicating that he likes them, and can also filter and delete records.


Application home page


Recipe creation page

Web components


Creating web components is easy. In particular, we are talking about creating a class that extends HTMLElement(or HTMLParagraphElement, and so on) and the subsequent use of this class to describe its own element.

In addition, when working with Web components, you can use the hooks of their life cycle, such as connectedCallback, disconnectedCallback, attributeChangedCallback.

Here is the component code recipe-itemthat is intended to display the recipes in the list.

import template from'./recipe.html'import DATA_SERVICE from'../../utils/data'exportdefaultclassRecipeextendsHTMLElement{
  constructor () {
    // подключаем теневую DOM, инициализируем приватное свойство recipe и DATA_SERVICE()
    super()
    this._shadowRoot = this.attachShadow({ mode: 'open' })
    this._recipe = null
    this.ds = new DATA_SERVICE()
  }
  connectedCallback () {
    // устанавливаем в качестве html-содержимого импортированный шаблон
    this._shadowRoot.innerHTML = template
    // прикрепляем метод delete к соответствующей кнопке
    this._shadowRoot
      .querySelector('.delete')
      .addEventListener('click', () => this._delete())
  }
  _render (title) {
    // задаём заголовок рецепта и текст кнопки, позволяющей отметить рецепт
    this._shadowRoot.querySelector('.recipe-title').innerHTML = title
    this._shadowRoot.querySelector('.favorite').innerHTML = this._recipe
      .favorite
      ? 'Unfavorite'
      : 'Favorite'
  }
  _delete () {
    // удаление рецепта или вывод сообщения об ошибке
    try {
      awaitthis.ds.deleteRecipe(this._recipe.id)
    } catch (e) {
      console.error(e)
      alert(
        'Sorry, there was a problem deleting the recipe. Please, try again.'
      )
    }
  }
  get recipe () {
    // геттер для рецепта
    returnthis._recipe
  }
  set recipe (recipe = {}) {
    // сеттер для рецепта, вызывающий метод render
    this._recipe = recipe
    this._render(this._recipe.title)
  }
}
window.customElements.define('recipe-item', Recipe)

Routing


The routing scheme of this application is also quite simple. When a navigation related event occurs, the application displays the corresponding component.

Initially, I used the Vanilla JS Router npm package to organize navigation in the application. But, using the API History , it is not hard to implement your own router, which will need about 100 lines of code. Notice that in this example, something really complicated is not implemented, like the means to restrict access to certain routes (route guard).

import'./components/error/error'import content404 from'./components/404/404.html'import DATA_SERVICE from'./utils/data'const ds = new DATA_SERVICE()
// получаем элемент, содержащий SPAconst $el = document.getElementById('app')
// объявляем маршрутыconst home = async () => {
  awaitimport('./components/recipe/recipe')
  awaitimport('./components/recipe-list/recipe-list')
  awaitimport('./components/modal/modal.js')
  $el.innerHTML = `<recipe-list></recipe-list>`
}
const create = async () => {
  awaitimport('./components/create-recipe/create-recipe')
  $el.innerHTML = `<create-recipe></create-recipe>`
}
const edit = async () => {
  awaitimport('./components/edit-recipe/edit-recipe')
  $el.innerHTML = `<edit-recipe></edit-recipe>`
}
const error404 = async () => {
  $el.innerHTML = content404
}
// установление соответствия маршрутов и путей// получение рецепта по id для создания маршрута редактирования рецептаconst routes = {
  '/': home,
  '/create': create,
  '/error': error404,
  '/edit': asyncfunction (params) {
    const id = params.get('id')
    const recipe = await ds.getRecipe(id)
    await edit()
    $el.querySelector('edit-recipe').recipe = recipe
  }
}
// по событию onpopstate получить параметры из URL и передать их маршруту// если нужного маршрута найти не удаётся - использовать маршрут /errorwindow.onpopstate = async () => {
  const url = new URL(
    window.location.pathname + window.location.search,
    window.location.origin
  )
  if (routes[window.location.pathname]) {
    await routes[window.location.pathname](url.searchParams)
  } else routes['/error']()
}
// добавление маршрута в историю браузераlet onNavItemClick = async pathName => {
  const url = new URL(pathName, window.location.origin)
  const params = url.searchParams
  if (routes[url.pathname]) {
    window.history.pushState({}, pathName, window.location.origin + pathName)
    await routes[url.pathname](params)
  } else {
    window.history.pushState({}, '404', window.location.origin + '/404')
    routes['/error']()
  }
}
// установка подходящего маршрута при загрузке и перезагрузке страницы
;(async () => {
  const url = new URL(
    window.location.pathname + window.location.search,
    window.location.origin
  )
  if (routes[window.location.pathname]) {
    await routes[window.location.pathname](url.searchParams)
  } else routes['/error']()
})()
// экспорт маршрутов и метода onNavItemClick()const router = {
  onNavItemClick,
  routes
}
export { router }

Here is a brief overview of the main building blocks of the application, since we do not need its full description here. In fact, in addition to the described features, it also implements others - such as endless scrolling and an interface for uploading pictures to the site by dragging them to the appropriate place on the page.

Comparing development using JS and frameworks


After the application was created, I thought a little about the strengths and weaknesses of the approach used in its development. I propose to consider them, starting with the drawbacks of the rejection of the JS frameworks.

Cons of rejecting frameworks


Станд Problems of standardization


Web component specifications, on the one hand, have been around for quite some time, but on the other, they are still evolving. So, the web components were presented by Alex Russell at the Fronteers Conference 2011 event. However, serious work in the direction of their support and development is carried out only in the last year or two. As a result, there is still confusion in the specifications. For example, the technology of HTML imports is no longer relevant , although it is written about in the documentation and in various publications.

▍Testing


There are not many solutions for testing standard web components. So, there are some promising tools - like skatejs ssr or web-component-tester . But these tools are designed for use with the appropriate libraries. As a result, someone who wants to use web components has certain difficulties.

Интерфейса Interface synchronization and application status



Constructions querySelector ()

When developing web applications, it is very important that a programmer has at his disposal some kind of basic system that automatically synchronizes data and its presentation on the page. It is such systems that attract many to Angular and to other frameworks.

If we are talking about small projects, the synchronization of the state of the application with its visual presentation is not a particularly difficult task. But during the growth of the project, synchronization can quickly become a problem, the developer, in order to support the application in a healthy state, will have to add to it many event listeners and item selection commands.

ShShadow DOM Technology


I still doubt the Shadow DOM technology. On the one hand, I like the idea of ​​encapsulation. This is an adequate design pattern that simplifies the management of styles and facilitates the work of the programmer. But, on the other hand, its use is fraught with difficulties, if it is necessary that something go beyond the boundaries of encapsulated entities. For example, it concerns the use of common styles. The question of how to use them correctly is still open .

▍Work with DOM


Frameworks and libraries like Angular and React owe their appeal to the fact that they greatly simplify working with the DOM. Namely, they do a great job when displaying and updating items. This is what Angular University’s blog says : “Angular directly generates DOM data structures, but doesn’t work by creating HTML code and then passing it to the browser for further processing.”

Angular, for example, unlike jQuery, directly generates DOM data structures. This is done instead of transferring to the browser HTML-code, which, before entering the DOM, should be parsed. Such an approach is more efficient because it eliminates the step of parsing HTML code. Virtual DOM technology is also very useful, as it eliminates the need to re-render the entire content of the page, performed every time you update certain elements.

We considered the disadvantages of not using frameworks in favor of the usual JS. Now let's talk about the pros.

Advantages of non-frameworks


▍Application package sizes


A package of a ready-made web application developed on pure JS may turn out to be (pay attention to the word “may”) much less than a package of a similar application created using frameworks. For example, the package of our ready-made experimental application that implements many possibilities is three times smaller than the package of an empty Angular application.


Empty Angular Application Package


A package of an application developed without frameworks.

▍Use of frameworks and understanding of technologies


If you developed web applications solely using some frameworks and their CLI, in order to create an application without supporting tools, you will have to really try. Creating projects without frameworks allows you to explore the basic technologies, tools and design patterns that underlie modern web development. This knowledge, in any case, whether you will acquire frameworks, use frameworks, or will not, will be useful.

▍Performance


What is being done in the depths of frameworks and libraries, allows you to get great results. But you have to pay for everything. In this case, the price of convenience is performance. At the same time, with an increase in the size of the application based on a certain framework, the load on the system created by the auxiliary mechanisms responsible for the operation of such an application can also increase. The system is loaded with unnecessary operations for updating pages, redundant event listeners, a deep comparison of objects, without which it is possible to do without unnecessarily large-scale manipulations with the DOM. You can get rid of all this simply by doing it yourself.

I would like to note here that the React and Angular development teams are obviously aware of such problems. Therefore, they pay considerable attention to optimizing their projects. For example, we are talking about something like using the React method shouldUpdate()or the strategy for detecting changes onPushin Angular.

▍Easy solutions and the problem of using someone else's code


Using someone else's code in your own projects is always a risk. If we are talking about well-tested and repeatedly tested frameworks in practice, this risk is reduced. But he always exists. If you can afford to write code yourself, whether it’s about an independent programmer or a team, you can reduce this risk. In addition, as you will be perfectly oriented in the code of their own projects.

Some notes and interesting observations


I really enjoyed working with Parcel. When I was looking for ways out of difficult situations, I felt limited a little more than when working with a Webpack, but I found out that, for the most part, the statement that Parcel does not need to be customized reflects the true state of affairs.

Earlier, I was inclined to think of React, Vue and Angular as means for solving the same problems. Therefore, I called them all "frameworks". However, it is now clear to me why React is more correctly called “library”, and Vue - “progressive framework”.

Why I did not use Stencil or Polymer? The fact is that when working on the project considered here, I tried not to use any packages, libraries or frameworks. True, this does not apply to the means of assembling projects. I wanted to see firsthand what the modern web developers are able to offer to a modern developer.

I am sure that there are many approaches to the development of SPA or front-end applications without the use of frameworks or libraries. Here I talked about how one of them tried, but in no way does it limit the capabilities of those who want to create applications with minimal use of someone else's code.

Basic technologies or frameworks?


In deciding whether a framework is necessary or not in a certain project, you can apply one excellent method, which I call the “tipping point method”. The point is that, during the growth and development of the application, there comes a time when the developer finds himself creating his own framework, aimed at ensuring the possibility of reusing certain functionality and structures. For example, this can happen if you have a lot of forms, and you want to create a code for reactive verification that is suitable for reuse.

If your project has grown to such a level, then you will need to decide whether to invest time in creating a system that implements the same features as a framework or a library. Such “critical moments” can occur at different stages of the project life. It depends on the amount of time that a programmer or team has, and on the amount of development funding. But it should be noted that the frameworks, if applied correctly and appropriately, perfectly show themselves in the development of web projects.

Thus, we can say that, over time, most of what is done using frameworks will probably be easier to do with smaller libraries or without supporting tools at all. For example, take a look at my application. At the same time, if large frameworks can flexibly respond to what is happening, they will be able to change, adapt and not lose relevance in the future. If not, then with the development of basic web technologies, they can, like jQuery today, lose most of their attractiveness.

Results


As a result, we can say that a promising approach to creating complex applications without using frameworks is available to a modern web developer. However, the specifications of technologies like web components are still in the process of development, and for their serious practical application you need to deal with something else. At the same time, frameworks are still systems that have many great features that can make the development of web applications a much more stable process than development without using them.

Today, the advantages of using frameworks in web development often outweigh their disadvantages. However, if the frameworks do not begin to solve new problems and do not continue to evolve, they, in the end, have every chance of becoming a thing of the past.

Dear readers! Have you developed web applications, aiming at minimal use of someone else's code?

Also popular now: