实现axios-环境搭建

478 阅读3分钟

小知识,大挑战!本文正在参与「程序员必备小知识」创作活动​​

前言

最近简单的学习了TypeScript的简单用法,忙里偷闲还研究了axios的源码,为了检验自己对TypeScript的掌握程度以及加深对axios源码的理解,决定使用TypeScript进行axios的重写。

插件选择

  1. rollup
  2. babel
  3. eslint

安装插件

创建文件夹 ts-axios

初始化项目

npm init -y
// 使用默认参数

安装 TypeScript

yarn add -D typescript
// -D 开发时用 
创建 src 目录,入口文件,以及 ts 的配置文件
ts-axios
 |
 |- src
 	 |- index.ts
 |- tsconfig.json

!!! 请勿忘记 package.json 里面的 "main": "src/index.ts",

配置 tsconfig.json
{
    "compilerOptions": {
    // 基础配置
    // 生成 .js 文件版本
      "target": "esnext",
      "lib": [
        "dom",
        "esnext"
      ],
      "removeComments": false,
    // 生成对应的 .d.ts 文件
      "declaration": true,
    // 生成 .map 文件
      "sourceMap": true,
    // 强类型检查配置
      "strict": true,
    // 存在隐式 any 时抛错
      "noImplicitAny": false,
    },
    "include": [
      "src"
    ]
  }

安装eslint

TypeScirpt 已全面采用 ESLint 作为代码检查

eslint提供了 TypeScript 文件的解析器 @typescript-eslint/parser 和配置选项 @typescript-eslint/eslint-plugin

yarn add -D eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin 
创建eslint的配置文件 .eslintrc.js
module.exports = {
    "parser": '@typescript-eslint/parser', //定义ESLint的解析器
    "extends": ['eslint:recommended', // eslint 推荐规则
        'plugin:@typescript-eslint/recommended', // ts 推荐规则
    ],//定义文件继承的子规范
    "plugins": ['@typescript-eslint'],//定义了该eslint文件所依赖的插件
    "env": {                          //指定代码的运行环境
        browser: true,
        node: true,
        es6: true,
    },
    // 配置规则
    "rules":{
        'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
        'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
        'array-bracket-spacing': 2,
        'no-var': 2,
        'no-eval': 2,
        'arrow-spacing': 2,
        'block-spacing': 2,
        'brace-style': 2,
        '@typescript-eslint/interface-name-prefix': 0,
        '@typescript-eslint/explicit-function-return-type': 0,
        '@typescript-eslint/no-empty-function': 0,
        '@typescript-eslint/no-var-requires': 0,
        '@typescript-eslint/no-use-before-define': 0,
    }
}
配置packagejson 脚本
"lint": "eslint src",
// 执行yarn lint 即可对指定文件进行检查     
VSCode 安装eslint 插件并启动 可以实时在控制台看到提醒

安装rollup和babel

rollup-plugin-babel 适用于 Rollup 的 Babel 插件

yarn add -D rollup rollup-plugin-babel rollup-plugin-commonjs rollup-plugin-eslint rollup-plugin-node-resolve rollup-plugin-typescript2 @babel/preset-env  @babel/core

创建Rollup的配置文件 rollup.config.js
import path from 'path'
import rollupTypescript from 'rollup-plugin-typescript2'
import babel from 'rollup-plugin-babel'
import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import { eslint } from 'rollup-plugin-eslint'
import { DEFAULT_EXTENSIONS } from '@babel/core'

import pkg from './package.json'

const paths = {
  input: path.join(__dirname, '/src/index.ts'),
  output: path.join(__dirname, '/dist'),
}

// rollup 配置项
const rollupConfig = {
  input: paths.input,
  output: [
    {
      name:'axios',
      file: path.join(paths.output, 'index.umd.js'),
      format: 'umd',
    },
  ],
    
  // external: ['lodash'], // 指出应将哪些模块视为外部模块,如 Peer dependencies 中的依赖
  // plugins 需要注意引用顺序
  plugins: [
    // 验证导入的文件
    eslint({
      throwOnError: false, // lint 结果有错误将会抛出异常并且阻止打包继续执行
      throwOnWarning: false,// lint 结果有waring将会抛出异常并且阻止打包继续执行
      include: ['src/**/*.ts'],
      exclude: ['node_modules/**', 'lib/**', '*.js'],
    }),

    // 第三方的模块为了能够直接使用,
    // 往往不是ES6模块而是用commonjs的模块方式编写的,
    // 这个时候我们需要将commonjs的模块转化为ES6模块,
    // 这样才能让rollup进行正确的解析。
    commonjs(),
    // 配合 commnjs 解析第三方模块
    resolve({
      // 将自定义选项传递给解析插件
      customResolveOptions: {
        moduleDirectory: 'node_modules',
      },
    }),
    rollupTypescript(),
    babel({
      runtimeHelpers: true,
      exclude: 'node_modules/**',
      // babel 默认不支持 ts ,需要手动添加
      extensions: [
        ...DEFAULT_EXTENSIONS,
        '.ts',
      ],
    }),
  ],
}

export default rollupConfig

!!! 为了直接在html中引入自己的axios

  <script src="../../lib/index.umd.js"></script>
  <script>
      axios({})
  </script> 

我们使用umd方式进行打包,并且制定了全局名称为axios

配置packagejson 脚本
"build": "rollup --c rollup.config.js",
// 执行yarn build 进行打包

最终目录

  • dist 打包文件
  • example 下篇文章会介绍,用来测试
  • src 核心代码
  • server.js 测试服务器