This is the 8th day of my participation in the First Challenge 2022. For details: First Challenge 2022.

Written in the beginning

Hello ~ everyone friends happy New Year ^-^, the New Year to me each other roll up!

I found time to write a column on the ElementUI source code series over the New Year and, as I expected, the reading and likes were dismal. But that doesn’t matter, it doesn’t stop my enthusiasm, this, without stopping to bring you the second source code series – Axios.

Of course, you didn’t think Axios was over, did you? Too naive, the third source series – VUe-CLI, I have been ready, if the recent work is not busy, I will update at the same time, hey hey, the New Year continue to roll up XDM.

Preliminary knowledge

Those of you who have used Axios should know that it is a tool for making web requests. Axios is a web request library based on Promise objects that can be used in browsers and Node.js environments.

Since network request is involved, before we introduce it formally, let’s build a network service to facilitate our subsequent test operations. There are many ways to build a service, you can choose the way you like, but this chapter we introduce a module – jSON-server, it can help us to quickly build a zero code, complete, convenient service in 30 seconds.

Json – server module

Global installation:

npm install -g json-server
Copy the code

Create a xxx.json file:

{" posts ": [{" id" : 1, "title" : "axios source series", "author" : "orange someone"}, {" id ": 2," title ":" json - server use tutorial ", "author" : "Orange someone}]," "profile" : {" name ":" orange someone ", "age" : 18}}Copy the code

Start the service:

json-server --watch xxx.json
Copy the code

If you can see such an interface, you have succeeded.

You can access these two interfaces directly through the browser. They support GET and POST requests. For more tips on how to use them, please refer to the official instructions.

Project preparation

With a back-end service in place, we can begin to structure the project.

First, find a good place on your computer, create a folder, and initialize the package.json file with the command NPM init -y. Create the index.js entry file in the project root directory. It is the total entry file for our project.

// index.js
module.exports = require('./lib/axios');
Copy the code

Let’s go ahead and create the lib folder, which will hold all the source code for Axios; Create the axios.js file.

// lib/axios.js var axios = {name: 'orange'}; module.exports = axios;Copy the code

The basic structure of the project is as follows:

Project package

After building the basic structure of the project, the next step is to package the project. The Axios packaging tool is Grunt and Webpack. Webpack is probably familiar to you, which is a module packer.

The Grunt is, to some extent, out of the picture. Grunt is the only code you need to understand. The following is the code for Grunt.

So without further ado, let’s take a look at how we can actually package our current project and practice the truth.

Download the dependencies first:

NPM install [email protected] [email protected] [email protected] [email protected] -dCopy the code

Then create gruntfile.js in the root directory with the following contents:

Module.exports = function(grunt) {// Load all dependencies required by the current project, LoadNpmTasks ("grunt-webpack") require('load-grunt-tasks')(grunt); loadNpmTasks("grunt-webpack") require('load-grunt-tasks'); // Grunt task total configuration grunt. InitConfig ({PKG: Grunt. File. ReadJSON (' package. Json), / / configuration details about webpack attributes can be seen here https://www.npmjs.com/package/grunt-webpack webpack: MyConfig: {mode: 'development', entry: './index.js', output: {path: __dirname + '/dist/', filename: 'axios.js', library: 'axios', libraryTarget: 'umd' }, } } }); / / register a task, specific syntax can be seen here https://www.gruntjs.net/creating-tasks grunt. RegisterTask (' build ', 'task description, such as: This is a task to pack Axios ', ['webpack']); }Copy the code

Once the project configuration file is created, we can execute the package command: Grunt Build.

If you can see a screen like the one above and generate dist/axios.js, you’re done.

Here are some tips you might be wondering about:

  • Above we used the load-grunt- Tasks module to automatically load the required dependencies, It is to actually read the package. The json file dependencies devDependencies/peerDependencies/optionalDependencies attribute to introduce related dependency. Or you can introduce dependencies the old way:

    module.exports = function(grunt) { grunt.loadNpmTasks("grunt-webpack"); grunt.initConfig({ ... }); // Register a task grunt. RegisterTask ('build', 'task description, e.g., this is a task to package Axios ', ['webpack']); }Copy the code

    This way you don’t have to download the load-grunt- Tasks module.

  • Grunt build command build is the name of the registered task.

    module.exports = function(grunt) { require('load-grunt-tasks')(grunt); grunt.initConfig({ ... }); // Register a task grunt. RegisterTask ('build', 'task description, e.g., this is a task to package Axios ', ['webpack']); / / register a task, more grammar can view: https://www.gruntjs.net/creating-tasks grunt. RegisterTask (' myTask '() = > {the console. The log (' my tasks'); }); }Copy the code

    Then you can executegrunt myTaskCommand.

  • Do you ever wonder, why not just use Webpack instead of Grunt? First of all, I have to say that there are a lot of similarities between the two, but you need to distinguish the essential differences. Webpack is a module packer and Grunt is a task executor. The so-called task executor is designed to automate common development tasks such as project code checking (Lint), building (build), testing (test), etc. It focuses on upper-level problems. Webpack focuses more on packaging between modules.

    The wrapper helps you take JavaScript and stylesheets ready for deployment and convert them into a usable format for your browser. For example, JavaScript can compress, split chunks, and lazily load to improve performance. Packaging is one of the most important challenges in Web development, and solving it can eliminate most of the pain points in the development process.

Project test

Now that the preliminary preparation of the project is finally done, let’s step into the test process. The test process is relatively simple, we directly create a new index.html file:

<! DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, Initial - scale = 1.0 "> < title > Axios < / title > < script SRC =" https://unpkg.com/axios/dist/axios.min.js "> < / script > < / head > <body> <script> axios({ url: 'http://localhost:3000/posts', }).then(res => { console.log(res) }) </script> </body> </html>Copy the code

We can first pull an official version of axios to recall the original use of axios. The result is normal:

Then we’ll test with axios written by our own project:

<! DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta Name ="viewport" content="width=device-width, initial-scale=1.0"> <title>Axios</title> /dist/axios.js"></script> </head> <body> <script> console.log(axios); // Print our own axios </script> </body> </ HTML >Copy the code

However, our current axios is just a simple object that we will refine over time.




At this point, this article is finished, sa Hua Sa hua.

I hope this article has been helpful to you. If you have any questions, I am looking forward to your comments. Same old, likes + comments = you know it, favorites = you know it.