Front-end frameworks are an important topic, and we will discuss frameworks in the following ways

  • Why you need a framework
  • What specific problems the framework needs to solve
  • What are the solutions to the problem

We will explain React and Vue in detail in another article, so this article will not cover them in too much detail.

1 Why do WE need frameworks

In the process of using JS, we will take some solutions to common problems out of the reuse, which is called library, such as jquery and LoDash. We can use the former to operate DOM, and use the latter to encapsulate some common functions.

While most of our daily development is the whole website, namely Web Aplication, using the framework makes it easier for us to develop web applications with high quality, and achieve predictability and homogeneity. Predictability ensures maintainable even when the application is developed. The framework is a special kind of library.

The biggest reason why a Web application needs to introduce a framework is to solve the synchronization problem between state and UI. If we implement it ourselves, we need to create the DOM directly with a lot of imperative code, and modify the DOM directly according to the state. Although jquery and other libraries have greatly improved the operation. However, The maintenance of The state and The synchronization of The corresponding UI can still be cumbersome and low performance, refer to The Example of The System Reason Why Modern JavaScript Frameworks exist.

Frameworks such as Vue and React can change the synchronization of state and UI from verbose imperative operations to concise declarative operations (see the programming paradigm for the difference between imperative and declarative operations).

The framework itself and its associated ecology also made our development more productive with less effort.

Other references:

  • Introduction to client-side frameworks

What problems did the framework solve for us

Front-end framework is a complete set of solutions including related JS framework as the core, and VUE includes vUE core, VUE-Router, VUEX and other complete solutions, so it calls itself framework on the official website.

Vue (pronounced /vju /, like view) is a progressive framework for building user interfaces. The core library is focused on the view layer only.

React, on the other hand, only provides the core library. Other solutions are provided by the community, so React calls itself a library.

React: A JavaScript library for building user interfaces

Other functions of a complete Web application are performed by other libraries in the ecosystem, such as state management tools, routing, and so on.

2.1 What problems should the framework core library solve

We have already known that the framework core solves the problem of page construction, now we need to further determine the specific problem. In order to understand the details of the framework core library, we will debug a framework core library, namely Preact, which is a popular class react library. The external UI is similar to React, but the implementation is relatively simple.

2.1.1 debugging preact

Set up the debug environment here

  • Create a simple Preact application with webpack-dev-server using WebPack (see webPack here)
  • Download Preact and follow here to download and configure the associated Babel
  • Create an entry file
//src/index.js import { h, render } from "preact"; import { useState } from "preact/hooks"; const App = () => { const [state, setState] = useState(1); return ( <div> <div onClick={() => { setState((v) => v + 1); }} > </div> {state} </div>); }; render(<App />, document.body);Copy the code
  • Since we import the packaged version by default, we need to modify the node_modules directory separately, Preact/package. Json and, preact/hooks/package. The json module in the field of “SRC/index. Js” in order to use the development version for debugging (package. Json documents related to introduce the reference here).

The core library of the framework generally realizes two parts of the function, one is the first rendering, one is to trigger the re-rendering through the modification state such as interaction, we started the Webpack development environment to debug in turn

For the first rendering, state dependent logic is not discussed

  • JSX grammar<App/>Will first callcreateElement()Method, and throughcreateVNodeReturn the vNode object
  • callrender()Method, where the first argument is the previously returned VNode, the second is the DOM node mounted by the view, in this case the body element, and then sets a commitQueue, modified with the diff element, and calls commitRoot commit
    • The diff function compares the two changes and updates them
    • callcommitRoot()The arguments are CommitQueue and vNode, respectively, and the CommitQueue is iterated over, then the respective callbacks are invoked to perform the associated side effects

Modify the state of

  • Called when the component is initialized for the first renderingconst [state, setState] = useState(1), actually calleduseReducer(), returns an array containing the state and setState functions, and displays the initial values at the corresponding positions on the page
  • Click the corresponding element to triggersetState()Method, callComponent.prototype.setState()andenqueueRenderAdd the elements that need to be updated to the render queue
  • calldefer()Method asynchronous invocationprocess()To call components in the render queue with the dirty attribute truerenderComponent()Method, which is called separatelydiff()andcommitroot().

2.1.2 inductive

A front-end framework core library needs to solve the following problems

  • An event system that listens for events
  • Component design questions, how is the code organized, including CSS, etc.
  • Change detection to determine which components have changed

2.2 What problems need to be solved in framework-related libraries

Once we have the framework core, a Web application also needs its ecology to solve the following problems

  • Data Management issues
  • Front-end routing problem
  • Development environment issues that provide scaffolding out of the box
  • Server rendering problem
  • Code debugging problems

Additionally, network requests and various UI libraries are beyond the scope of this discussion.

3 Solution

This chapter will discuss the solutions and related concepts to the problems to be solved in the previous chapter

  • Introduction to client-side frameworks
  • Qunar mini React
  • Don’t blow don’t black chat front frame was originally a live of Rain Creek, the link is a tidy note
  • Presentational and Container Components
  • Evan You on Vue.js: Seeking the Balance in Framework Design

3.1 Event System

The browser’s own event system, which you can refer to here, has two problems when developing a project

  • Re-rendering the DOM requires re-registering and listening for events in the corresponding DOM, resulting in performance loss
  • Different browsers have different implementations, resulting in compatibility problems

For these reasons, a framework will typically further encapsulate its own event system, such as react’s composite event.

3.2 Component design issues

Components are solutions that separate parts of the UI and internal logic (or even just logic) to improve maintainability and reusability, similar to the Web Components in the HTML5 specification, which are more mature.

Private state can be maintained within components, and components can communicate with each other. They can be nested, and the application can be organized into a tree structure through inheritance and composition.

3.2.1 Component Classification

A component can be a function or a class, depending on how it is written, but there is no real difference between them. According to the role to distinguish, can be divided into the following kinds

  • Pure presentation components that input data and output the DOM, such as presentational Components in React
  • The access component, which contains data interaction with the server and is used to pass data to the presentation component, such as the Container Components in React
  • Interactive components are components that primarily solve interactive problems and can be generic, such as elementUI
  • Functional components that do not output UI and are used for reuse logic, such as router-View components and Transition components in VUE

3.2.2 Templates and JSX

Templates and JSX are the two main forms of code organization in front-end UI construction.

Libraries represented by React use JSX, which can organize logic as freely as ordinary JS, so it is difficult to predict users’ usage patterns in a controllable way and make efficient optimization. The next step of JSX is to generate virtual DOM for diff rendering. This amount of work means that we need to add a lot of runtime code from the library itself to our production code.

Libraries, such as Svelte, use templates that follow specific rules, which means that the compiler can handle the writing of finite rules and modify the CORRESPONDING DOM without the need for the Virtual DOM, for example

Libraries with associated design ideas also have less Runtime code.

The design of VUE takes into account the two writing methods, which can use JSX to give users freedom of writing and provide templates to increase the space for optimization. However, VUE2 will unify these two writing methods into virtual DOM and does not make full use of the advantages of templates. This point has been optimized for templates in VUe3.

3.2.3 Code splitting

And traditional according to the language to split, and after the introduction of components, the organization of code to components as a unit, representing UI and logic HTML and JS basic no objection, for CSS processing also exist the following scheme, the final result is to ensure the uniqueness of class names in different components.

  • The traditional scheme uses schemes such as BEM to create global styles
  • CSS Module: Modular CSS
  • Css-in-js is used in the React ecosystem
  • Single-page component CSS, such as scoped in Vue

For details about the CSS solutions, see here.

3.3 Change Detection

This is basically the core function of a framework, and is also a key factor in determining the performance of a framework

3.3.1 Detection scheme

As mentioned earlier, the framework will change the original imperative modification dom writing to declarative writing, and the framework to ensure that the state changes can be refreshed in time, the first must be able to effectively listen for changes, including two main types of change listening

  • Pull means that the framework does not know whether the data has changed, but only that it may have changed due to related events. Therefore, it needs to perform a comparison to find out the specific change location. The comparison process, such as React and preact mentioned earlier, can cause performance waste.
  • The finer the granularity of the monitoring, the more accurate the location of the change. But this also means that the related observabel/ Watcher incurs the overhead of memory and dependency tracking. The implementation of VUE is to inject medium-granularity monitoring and perform diff on a small scale, that is, the combination of the two solutions.

React is the VIEW layer in MVC. It will update the view after the model changes, instead of making the view update the model synchronously. Users can complete this action in the node binding event, which belongs to push. Model changes in turn cause the entire subtree to be recalculated (with optimization points, of course). The view is monitored at the appropriate level, and is event-bound in the framework for the user’s view changes, so that model updates are triggered when the user changes the view, and MVVM is implemented.

3.3.2 Virtual DOM and DIff algorithm

Dom is an object with a large number of attributes implemented by browsers. Some front-end frameworks maintain one or more data structures corresponding to real DOM nodes in memory. This data structure is called virtual DOM, that is, virtual DOM. This data structure is a common JS object. The specific implementation of a specific Virtual DOM varies, but each virtual DOM contains some basic properties, such as Type, props, and children. Manipulating each real DOM node is much more performance expensive than the corresponding virtual DOM node, but this is not the most important reason to use the virtual DOM. The basic meaning of using the virtual DOM is to use it as a general means of framework declarative state synchronization UI (while the overall performance is not necessarily better than native JS operations). A manually optimized direct manipulation of the DOM is faster than a virtual DOM because diff itself is a performance drain. The introduction of the virtual DOM makes sense for two reasons

  • You can use functional programming UI
  • As an intermediate step, the virtual DOM can actually be rendered to places outside the DOM, such as Rn.

There are many common virtual DOM implementations, such as virtual-DOM at the very beginning. Each virtual DOM corresponds to a diff algorithm. The related evolution is shown in the figure

However, the diff algorithm of the virtual DOM itself is a kind of performance consuming work, constantly recursing diff, and finally finding a specific location that needs to be updated for re-renderingUnder this premise, there are two solutions. One is to give up the virtual DOM and the flexibility of JSX just like the aforementioned Svelte. The other is to focus on the perception of users after the performance of React cannot be further improved. In other words, the introduction of Fiber reduces the latency of virtual DOM processing and makes it feel faster.

3.4 Data Management

Namely, the state management scheme. The first front-end state management scheme is Facebook flux, and the subsequent state management tools follow a similar idea.

State can be regarded as the model in the mv* architecture of the front end. In order to synchronize the model and view reasonably, a state management tool should have the following two characteristics:

  1. Clear data flow. Data in an application is generally shared by multiple components, and status changes affect multiple components. Therefore, clear data flow must be ensured.
  2. Bind the state to each corresponding component for component update

A state management tool typically sets up one or more stores for data management.

How to understand Redux in plain English

3.5 Front-end Routing

The server route is defined in the Express documentation

Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).

Each route corresponds to a response to a request, which consists of a path and a method. Each time a traditional page is navigated, the client requests a new page from the server, the browser renders the new page, and saves the session history for forward/backward navigation.

However, modern Web applications are generally single page applications (SPA). Navigation does not need to request a new page to the server, that is, it can be realized by switching view. This navigation mode is called front-end routing or client-side routing, which is also one of the problems to be solved by the framework.

Front-end routes are essentially mappings between related states represented by urls and views. To ensure normal forward and backward navigation of traditional routes, two policies are generally adopted: Hash mode and history API, the former uses hashchange event listening, the latter uses methods such as pushState on history to modify the session history, both of which can modify the URL without refreshing, and can modify the session history to achieve the effect of server-side routing.

3.6 Development Environment Problems

As a complete solution for developing Web applications, the framework should provide a suitable development environment corresponding to the ecology, such as react Create App and VUE-CLI of Vue. Both packers are based on Webpack. Vue also provides vitejs, a development environment dedicated to VUE3. The packager is based on rollup. See the packager here.

The above tools greatly reduce the threshold to use the framework.

3.7 Server rendering Problems

When front-end SPA is widely used, its existing problems are still difficult to solve

  • Single page SEO is not friendly, Google and other search engines can not be asynchronously loaded page information included
  • The first screen shows the time, and the content of a single page needs to be further parsed before it can be rendered by calling relevant resources

There are other solutions to this problem, such as pre-rendering if you only care about certain pages, the prerender-spa-plugin for Webpack can solve this problem, and HTTP /2 server push can solve this problem. But nothing can be done about SEO.

Server rendering (SSR) is usually done by converting the virtual DOM into AN HTML string on the server side for display on the client side. Both Vue’s Nuxt.js and React’s next.js offer higher levels of encapsulation of this solution.

3.8 Code debugging Problems

Vue provides vue-devTools and react provides react-devTools to monitor development status and related events during actual development.


End and spend