The Greatness and Evil of Open Source
Tags: react, vue, svelte, axios
Published: 2023-07-30 09:01:10

**Recently, I found that many people’s thinking is still stay at usage, and lacks deeper understanding and thinking**. In this article, I want to talk about my deeper thoughts on open source frameworks and libraries, from a deeper perspective Talk about why I am optimistic about alova! ! !

** After reading it, I guarantee you will gain something. ** If you don’t know alova yet, you can learn about it first:

[alova's Github address](https://github.com/alovajs/alova)

[alova official website](https://alova.js.org/)

If you don't know axios, [click here](https://axios-http.com/)

> This article mainly discusses the things behind programming, rather than the solution of a certain technical point. Welcome everyone to participate in the discussion!

## Directory
1. The greatness of react and vue
2. What are the advantages of alova
3. A history of crime in open source frameworks

## The greatness of react and vue

What I deeply understand is that open source frameworks and libraries have really brought us too much convenience. Before discussing alova in depth, let's start with the most familiar UI frameworks such as react and vue.

What exactly do these UI frameworks bring us? The past king jquery can be said to dominate the world. The problem jquery solves is to provide a simpler and more compatible dom operation api, so that everyone does not need to pay attention to compatibility issues, but for For novices, they will still write all the code in a js file and then place the code randomly, let’s enjoy a piece of jquery code like instant noodles:

```js
// ❌The js processing of the entire page is concentrated here
(function(win) {
     // Handle header button click event
     $('#header.button').click(function() {
         //...
     });

     // Handle the mouse move event of a tag in the footer
     $('#footer.tag').mouseenter(function() {
         //...
     });

     // Handle the event of the main interface carousel
     $('#swiper.btn-left').mouseenter(function() {
         //...
     });
     $('#swiper.btn-right').mouseenter(function() {
         //...
     });
})(window);
```

The project is divided into large modules such as html, js, and css. The structure is roughly like this


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uixs1uj4hdfcfrl2djb1.jpg)

A mess of twisted and twisted codes, maintainability drops to negative points, whoever wants to take over will be unlucky, as the project becomes more and more complex, every change is like a hammer on the chest of the taker— — It’s extremely painful. As long as there are novices in the team, no matter how the technical leader formulates the specifications for module splitting, this kind of thing cannot be avoided. In the end, the receivers also threw away the offer...

**why?**

Because the leader's specifications are just **opinion-based specifications** written on the document, you can make the project run without following them. The advantages of MVVM UI frameworks (hereinafter referred to as UI frameworks) such as react and vue were immediately highlighted, which made them quickly defeat the past king jquery. The greatest thing about these UI frameworks is that they provide a A more maintainable code organization mode - **Componentization**, and force everyone to use this method to develop applications. In componentization, html, js, and css are aggregated with the component as the smallest unit, and the components are decoupled from each other, probably like this

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f6throguz60ba215159p.jpg)

They form a **constrained specification**, and you can’t run if you don’t follow the project. This method allows front-end developers in the world to reach a unified modular consensus, just like the power socket in your home.

**I think the above is the difference between a framework and a library! ! ! **

This kind of restrictive specification can make component libraries flourish, and various component libraries are born to further reduce the amount of development for everyone.

**This is the power of restrictive norms**, maybe you suddenly understand why you need to use husky.

The MVVM pattern using data-driven views, although compared with jq, is also a dimensionality reduction blow, but I think its importance is not as great as componentization.

> **IMPORTANT: In addition to standardizing variable names and comments, the purpose of formulating specifications is to achieve high aggregation and low coupling at the code organization level. ** I am no stranger, and I think vue's SCF and instructions are better than react's jsx has further achieved mandatory specifications.

# What are the advantages of alova?

If you understand the above specification questions, let's talk about what is so special about alova compared to `react-query`, `swr`, `vueuse's useFetch` and `ahook's useRequest`, etc.

The js library can be divided into a standard js library and a functional js library

## Specification-based js library

In addition to providing APIs, UI frameworks such as react and vue also provide componentization (constrained specifications), which are obviously normative libraries, that is, frameworks.

## Functional-based js library

For example, axios, moment, lodash, jquery, etc. are all functional js libraries. Their more value is to provide APIs that are easy to call, while react-query and swr are indeed pioneers in using use hook to manage requests and use request caching , but it seems that there is no normative shadow besides these, so it is more inclined to classify them into functional js libraries and paste examples.

## React-query official example

```js
function Example() {
   // Call fetch or axios to send requests in each useQuery, with a high degree of coupling
   // Need to maintain queryKey manually
   const { isLoading, error, data } = useQuery({
     queryKey: ['repoData'],
     queryFn: () =>
       fetch('https://api.github.com/repos/tannerlinsley/react-query').then(
         (res) => res.json(),
       ),
   })

   if (isLoading) return 'Loading...'
   if (error) return 'An error has occurred: ' + error.message
   return (
     <div>
       <h1>{data.name}</h1>
       <p>{data.description}</p>
       <strong>👀 {data.subscribers_count}</strong>{' '}
       <strong>✨{data. stargazers_count}</strong>{' '}
       <strong>🍴 {data. forks_count}</strong>
     </div>
   )
}
```

## swr official example

```js
// Coupling request
const fetcher = url => fetch(url).then(r => r.json())
function App() {
   const { data, error } = useSWR('/api/data', fetcher)
   //...
}

// way of decoupling
import useSWR, { SWRConfig } from 'swr'
function Dashboard () {
   const { data: events } = useSWR('/api/events')
   const { data: projects } = useSWR('/api/projects')
   const { data: user } = useSWR('/api/user', { refreshInterval: 0 }) // override
   //...
}
 
function App() {
   return (
     <SWRConfig
       value={{
         refreshInterval: 3000,
         fetcher: (resource, init) => fetch(resource, init).then(res => res.json())
       }}
     >
       <Dashboard />
     </SWRConfig>
   )
}
```

I think the vercel team has considered this point, but only considers the decoupling method as an option.

## alova's difference

Although alova is compared to axios, react query, swr and other senior big names, alova can only be regarded as a rookie among rookies. Other libraries have been developed for 5 to 10 years, and the author seems to be relatively low-key. But in my opinion, alova is more in-depth and thorough in solving ideas than its predecessors.

The author of alova proposed a model called [RSM Specification (Request Scene Model)](https://alova.js.org/tutorial/get-started/RSM), and let alova follow this model to design, the official sample code as follows:

```js
import { createAlova } from 'alova';
import GlobalFetch from 'alova/GlobalFetch';
import VueHook from 'alova/vue';

const alovaInstance = createAlova({
     // Suppose we need to interact with the server for this domain name
     baseURL: 'https://api.alovajs.org',

     // VueHook can help us use vue's ref function to create request-related states that can be managed by Alova
     statesHook: VueHook,

     // request adapter, we recommend and provide fetch request adapter
     requestAdapter: GlobalFetch(),
    
     // global pre-request hook
     beforeRequest(method) {
         //...
     },
    
     // global response hook
     responded: {
         onSuccess(response, method) {
             //...
         },
         onError(err) {
             //...
         }
     }
});

// Create a Get instance to describe the information of a Get request
const todoListGetter = alovaInstance. Get('/todo/list', {
     // request header
     headers: {
         'Content-Type': 'application/json;charset=UTF-8'
     },
     // The params parameter will be spliced after the url in the form of?
     params: {
         userId: 1
     },
    
     // Set the cache time for this request alone
     localCache: 50000,
     // Enable request sharing for this request alone
     shareRequest: true,
     // data conversion
     transformData(result) {
         //...
     },//...
});
```

From the above example, the following two advantages of alova can be seen:

1. Alova enforces decoupling of request tools and request methods in the form of request adapters, storage adapters, and UI framework adapters, achieving low coupling and improving code portability rather than options.
2. The Method concept in alova is used to implement the request behavior of RSM. It also forces the request-related information and request behavior-related information to be highly aggregated in the Method, which can manage the request-related code to a greater extent. There are more and more APIs for project management, and its advantages will gradually emerge, and the coding is more unified. At the same time, it maintains a high degree of flexibility and provides enough customization space for users.

**So, I would place alova somewhere in the middle between canonical and functional libraries**

Finally, the goal of alova is to realize the integration of development experience and user experience according to business scenarios, and alova's high flexibility can support custom strategies, and you can encapsulate the internal use of the company. For example, your company likes to use a certain Such processing to optimize performance, or write your own strategy library like an alova plug-in, then alova can just provide support.

Speaking of this, it seems that alova's use hook form is not so important.

# The history of crime of open source framework 

Both react and vue pay more attention to the UI level. They simplify the problems at the UI level, but as far as I understand, there is still no unified control specification or related js logic framework to solve this problem at the level of js logic. Novices and experts There is still a certain gap in the maintainability of the written code. While the UI framework simplifies things, it also fattens a bunch of lazy people who lie on the achievements of the UI framework. These people often have the following two problems:

1. Stop thinking about specification issues, boundaries and collaboration between modules, don't even realize that these things exist, and then write code everywhere regardless of responsibility, please imagine a dog pulling around..., and pile up What kind of mountain is it called?
2. They only enjoy the upper-level results, and no longer pay attention to the bottom-level things, even if they are a little bit lower-level, because they really don’t need them, just like we no longer pay attention to the problem of garbage collection (in C language, manual recycling is required), which is even more outrageous What's more interesting is that some people even do what `getElementById`, `appendChild`, `insertBefore` do, let alone ask them how many types of nodetype, what fragment is, whether comments are a kind of node, etc.

It is conceivable that there is a reason why there are fewer cutting-edge talents. You know why it is difficult to recruit advanced front-ends! ! ! Of course, there are also a small number of students who like to delve into it, and like to know what it is and why it is.

This seems to be an unavoidable side effect of the development of the times and the advancement of science and technology. Besides providing us with powerful and convenient tools, they are also slowly destroying such a large group of people. There is no need for so many heroes in peaceful times. This reminds me of the point of view in book called "Anti-Fragility" - modernization is the fragility of the world.

> Insert a digression. After all, react and vue take over the component specification at the UI level, but the specification at the js logic level is still in the document, and has not yet formed a restrictive specification. At this level, novice friends can also use them Written as spaghetti, interested students can also start to think about it. Is it possible to propose a restrictive specification from the js logic level, and then form a new js framework, just like the UI framework component specification. If someone does it, can you Come back and leave a message to tell me.

**After reading the article, let’s talk about what code specifications you understand?**