current position:Home>Typescript refactoring Axios (I)

Typescript refactoring Axios (I)

2021-08-21 18:30:31 Fall

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 https://github.com/alexjoverm/typescript-library-starter.git  Project name 

We initialize the project here

#  Pull down the project foundation template 
git clone https://github.com/alexjoverm/typescript-library-starter.git ts-axios-pro
#  Switch to the project directory
cd ts-axios-pro
#  Project install Install related plug-ins
npm install 

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

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: {
        noInfotrue,
        overlaytrue,
        opentrue,
        proxy: {
          //  Configure cross domain
          "/api/": {
            target"http://localhost:3000",
            wstrue,
            changOrigintrue
          }
        }
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoEmitOnErrorsPlugin()
    ]
}

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({ extendedfalse }));
app.use(bodyParser.json());


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

app.use(router)

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

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'
axios({
    method"get",
    url"/api/base/get",
    params: {
      a1,
      b2
    }
})
# index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Base demo</title>
</head>
<body>
<script src="/__build__/base.js"></script>
</body>
</html>

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

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

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[Fall],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210821183026015w.html

Random recommended