重构axios(版本1.4.0)

205 阅读3分钟

# axios 工程搭建

  • rollup.config.js 按源码配置增加typescript
import resolve from '@rollup/plugin-node-resolve'; //允许我们加载第三方模块
import commonjs from '@rollup/plugin-commonjs'; //插件将它们转换为ES6版本
import terser from '@rollup/plugin-terser'; //压缩,转译es6+语法,请改用terser
import json from '@rollup/plugin-json'; //可将.json文件转换为ES6模块
import { babel } from '@rollup/plugin-babel'; //正确解析我们的模块并使其与旧版浏览器兼容
import autoExternal from 'rollup-plugin-auto-external'; //自动添加至 externals 未免
import bundleSize from 'rollup-plugin-bundle-size'; //分析包大小工具
import ts from 'rollup-plugin-typescript2'; // typescript打包
// import serve from 'rollup-plugin-serve'; //服务
import path from 'path';
import fs from 'fs';
import { URL, fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const pkgPath = path.resolve(path.dirname(__filename), './package.json');
const __dirname = path.dirname(__filename);
const lib = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));

const outputFileName = 'axios';
const name = 'axios';
const namedInput = './index.ts'; //入口路径
const defaultInput = './lib/axios.ts';

const buildConfig = ({ es5, browser = true, minifiedVersion = true, ...config }) => {
  const { file } = config.output;
  const ext = path.extname(file);
  const basename = path.basename(file, ext);
  const extArr = ext.split('.');
  extArr.shift();

  const build = ({ minified }) => ({
    input: namedInput,
    ...config,
    output: {
      ...config.output,
      file: `${path.dirname(file)}/${basename}.${(minified ? ['min', ...extArr] : extArr).join('.')}`,
    },
    plugins: [
      json(),
      resolve({ browser, extensions: ['.js', '.ts'] }),
      commonjs(),
      ts({
        tsconfig: path.resolve(__dirname, 'tsconfig.json'),
      }),
      // serve({
      //   port: 8000,
      //   contentBase: '', // 表示起的服务是在根目录下
      //   openPage: 'index.html', // 打开的是哪个文件
      //   open: true, // 默认打开浏览器
      // }),
      minified && terser(),
      minified && bundleSize(),
      ...(es5
        ? [
            babel({
              babelHelpers: 'bundled',
              presets: ['@babel/preset-env'],
            }),
          ]
        : []),
      ...(config.plugins || []),
    ],
  });

  const configs = [build({ minified: false })];

  if (minifiedVersion) {
    configs.push(build({ minified: true }));
  }

  return configs;
};

export default async () => {
  const year = new Date().getFullYear();
  const banner = `// Axios v${lib.version} Copyright (c) ${year} ${lib.author} and contributors`;

  return [
    // browser ESM bundle for CDN
    ...buildConfig({
      input: namedInput,
      output: {
        file: `dist/esm/${outputFileName}.js`,
        format: 'esm',
        generatedCode: {
          constBindings: true,
        },
        exports: 'named',
        banner,
      },
    }),

    // Browser UMD bundle for CDN
    ...buildConfig({
      input: defaultInput,
      es5: true,
      output: {
        file: `dist/${outputFileName}.js`,
        name,
        format: 'umd',
        exports: 'default',
        banner,
      },
    }),

    // Browser CJS bundle
    ...buildConfig({
      input: defaultInput,
      es5: false,
      minifiedVersion: false, // 是否打包mini版本
      output: {
        file: `dist/browser/${name}.cjs`,
        name,
        format: 'cjs',
        exports: 'default',
        banner,
      },
    }),

    // Node.js commonjs bundle
    {
      input: defaultInput,
      output: {
        file: `dist/node/${name}.cjs`,
        format: 'cjs',
        generatedCode: {
          constBindings: true,
        },
        exports: 'default',
        banner,
      },
      plugins: [
        autoExternal(),
        ts({
          tsconfig: path.resolve(__dirname, 'tsconfig.json'),
        }),
        resolve({ extensions: ['.js', '.ts'] }),
        commonjs(),
      ],
    },
  ];
};


  • tsconfig.json

{
  "compilerOptions": {
    /* Basic Options */
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
    "module": "ESNext",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    "lib": ["es2015", "es2016", "es2017", "dom"],                             /* Specify library files to be included in the compilation. */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    "declaration": true,                 /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    // "outDir": "./",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true,                   /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
    "declarationDir": "dist/types",
    "typeRoots": [
      "node_modules/@types"
    ]
  },
  "include": [
    "lib",
    "index.ts"
  ]
}

一、官方案例(./sandbox/client.html)

 var options = {
    "url": "/api",
    "params": null,
    "method": "GET",
    "headers": null
};
 axios(options)
          .then(function (res) {
            response.innerHTML = JSON.stringify(res.data, null, 2);
            error.innerHTML = "None";
          })
          .catch(function (res) {
            error.innerHTML = JSON.stringify(res.toJSON(), null, 2)
            console.error('Axios caught an error from request', res.toJSON());
            response.innerHTML = JSON.stringify(res.data, null, 2);
          });

二、跑通该案列 (按源码思路修改代码)

  • 主入口
// index.js
import axios from './lib/axios.js';
export default axios
  • 实例化
// ./lib/axios.js
import Axios from "./core/Axios";
function createInstance() {
  const context = new Axios();
  const instance = async function () {
    return await context.request(...arguments)
  }
  return instance
}

const axios = createInstance()


export default axios

// 实例化
const axios = createInstance()

export default axios
  • Axios类(核心逻辑)
// ./lib/core/Axios.js
import dispatchRequest from './../request/xhr'
class Axios {
  constructor() {

  }
  async request(configOrUrl) {
    const config = Object.assign({}, configOrUrl)
    const res = await dispatchRequest.call(this, config);
    return res
  }
}
export default Axios
  • 请求
// ./lib/core/request/xhr.js
export default async function dispatchRequest(config) {
  
  const fullPath = config.url
  let request = new XMLHttpRequest();
  request.open(config.method.toUpperCase(), fullPath, true);
 // Send the request
  request.send(config.params || null);

 //监听请求变化
 request.onreadystatechange = function handleLoad() {
  // 请求错误
  if (!request || request.readyState !== 4) {
    return 
  }

  return onloadend()

}



// 函数
function onloadend() {
  console.log('响应:', request.response)
  return request.response
}
}

github地址:https://github.com/power812/power-project-dev/tree/dev/1.0.0/packages/power-fetch-axios