current position:Home>Typescript rewrites Axios

Typescript rewrites Axios

2021-08-27 02:00:26 Luoluo 947

TypeScript rewrite axios The birth of the project

Project initialization

We go through TypeScript library starter To create a TS project , It's open source TypeScript Developing scaffolding tools for basic libraries , Can help us quickly initialize a TypeScript project , We can go to its Official website Learn and use it .

One 、 Usage mode

git clone  Project name 
 Copy code 

We initialize the project here

#  Pull down the project foundation template 
git clone ts-axios-pro
#  Switch to the project directory 
cd ts-axios-pro
#  Project install Install related plug-ins 
npm install 
 Copy code 

Two 、 Project directory

Before writing code , Let's get to know axios workflow , As shown in the figure below :

We probably know axios workflow , Of course, if you read the source code , And understand that it's better , Next, let's write an example of the test , We're creating a... Under the following directory examples Catalog , stay examples Create one in the directory webpack.config.js The configuration file , Writing webpack.config.js Documents before , Let's install some plug-ins first :

  • npm install express -D install express frame , Write server code
  • npm install body-parser -D solve post request
  • npm install [email protected] [email protected] webpack-dev-server -D install webpack
  • npm install [email protected] tslint-loader -D One is parsing to .ts Final document , One ts Of eslint
npm install express -D
npm install body-parser -D
npm install [email protected] [email protected] webpack-dev-server -D 
npm install [email protected] tslint-loader -D
 Copy code 

After successful installation , Yes examples/webpack.config.js To configure

# webpack.config.js

const fs = require('fs');
const path = require('path');
const webpack = require('webpack');

module.exports = {
     *  We will be in  examples  Create multiple subdirectories under the directory 
     *  We'll take the different chapters  demo  Put it in different subdirectories 
     *  One will be created under each subdirectory  app.ts
     * app.ts  As  webpack  Build the entry file 
     * entries  Collected multiple directory entry files , And each entry also introduces a file for hot update 
     * entries  It's an object ,key  Name the directory 
    entry: fs.readdirSync(__dirname).reduce((entries, dir) => {
        const fullDir = path.join(__dirname, dir);
        const entry = path.join(fullDir, "app.ts");
        if (fs.statSync(fullDir).isDirectory() && fs.existsSync(entry)) {
        entries[dir] = entry;
        return entries;
    }, {}),
     *  According to different directory names , Package and build targets  js, The name matches the directory name 
    output: {
        path: path.join(__dirname, "__build__"),
        filename: "[name].js",
        publicPath: "/__build__/"
    resolve: {
        extensions: [".ts", ".tsx", ".js"]
    module: {
        rules: [
            test: /.ts$/,
            enforce: "pre",
            use: "tslint-loader",
            exclude: /node_modules/
            test: /.tsx?$/,
            use: "ts-loader",
            exclude: /node_modules/
    devServer: {
        noInfo: true,
        overlay: true,
        open: true,
        proxy: {
          //  Configure cross domain 
          "/api/": {
            target: "http://localhost:3000",
            ws: true,
            changOrigin: true
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoEmitOnErrorsPlugin()
 Copy code 

Server code

Create... In the root directory server Folder , stay server Create... Under file server.js

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const router = express.Router();

//  Use body-parser middleware 
app.use(bodyParser.urlencoded({ extended: false }));

router.get('/api/base/get', (req, res) => {
        msg: 'hello world'


const port = process.env.PORT || 3000;
module.exports = app.listen(port, () => {
    console.log(`Server listening on http://localhost:${port}, Ctrl+C to stop`)
 Copy code 

stay examples Let's build the first example : We call it base, It's a folder , It contains index.html and app.ts

# app.ts
import axios from '../../src/axios'
    method: "get",
    url: "/api/base/get",
    params: {
      a: 1,
      b: 2
 Copy code 
# index.html
<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8">
    <title>Base demo</title>
<script src="/__build__/base.js"></script>
 Copy code 

At this point we are package.json Set related commands :

//  stay scripts Add two lines of commands 
  "server": "node server/server.js",
  "dev": "webpack-dev-server --config './examples/webpack.config.js' --hot"
 Copy code 

We execute npm run dev It can make demo Run , At the same time, let the server start npm run server visit http://localhost:8080/, Such a small demo It was successful , For the next document, let's start writing axios The source of the ..

copyright notice
author[Luoluo 947],Please bring the original link to reprint, thank you.

Random recommended