前端工程化-Vite + Vue3 项目规范化配置

882 阅读15分钟

前端工程化-Vite + Vue3 项目规范化配置

简介

一个好的项目开始搭建总是需要配置许多初始化配置,比如eslint语法检验、prettier代码格式统一、husky做commit拦截等等,本文从零开始带你一步步搭建一个完整的项目配置,熟悉之后下次直接拿来即用

环境准备

1、node v16以上

2、pnpm 8.0以上

一、新建项目

npm i -g pnpm
pnpm create vite v3_ts_template

cd v3_ts_template

pnpm i

二、配置eslint

2.1 安装eslint

pnpm i eslint -D

2.2 生成eslint配置文件

pnpm eslint --init

2.2.1.这里我们选择选项二即可

eslint_1.png

eslint_2.png

2.2.2.选择第一项

eslint_3.png

eslint_4.png

2.2.3.第三问选择Vue.js

2.2.4.选择Yes,表示使用TS

2.2.5.选择Browser,表示代码运行在浏览器环境

2.2.6.选择JavaScript,表示生成js文件格式

2.2.7.选择Yes,表示安装校验vue以及ts语法的插件

2.2.8.选择pnpm,表示使用pnpm安装依赖

2.3 .eslintrc.cjs 选项推荐配置

// @see https://eslint.bootcss.com/docs/rules/

module.exports = {
    env: {
        browser: true,
        es2021: true,
        node: true,
        jest: true,
    },
    /* 指定如何解析语法 */
    parser: 'vue-eslint-parser',
    /** 优先级低于 parse 的语法解析配置 */
    parserOptions: {
        ecmaVersion: 'latest',
        sourceType: 'module',
        parser: '@typescript-eslint/parser',
        jsxPragma: 'React',
        ecmaFeatures: {
            jsx: true,
        },
    },
    /* 继承已有的规则 */
    extends: [
        'eslint:recommended',
        'plugin:vue/vue3-essential',
        'plugin:@typescript-eslint/recommended',
        'plugin:prettier/recommended',
    ],
    plugins: ['vue', '@typescript-eslint'],
    /*
     * "off" 或 0    ==>  关闭规则
     * "warn" 或 1   ==>  打开的规则作为警告(不影响代码执行)
     * "error" 或 2  ==>  规则作为一个错误(代码不能执行,界面报错)
     */
    rules: {
        // eslint(https://eslint.bootcss.com/docs/rules/)
        'no-var': 'error', // 要求使用 let 或 const 而不是 var
        'no-multiple-empty-lines': ['warn', { max: 1 }], // 不允许多个空行
        'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
        'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
        'no-unexpected-multiline': 'error', // 禁止空余的多行
        'no-useless-escape': 'off', // 禁止不必要的转义字符

        // typeScript (https://typescript-eslint.io/rules)
        '@typescript-eslint/no-unused-vars': 'error', // 禁止定义未使用的变量
        '@typescript-eslint/prefer-ts-expect-error': 'error', // 禁止使用 @ts-ignore
        '@typescript-eslint/no-explicit-any': 'off', // 禁止使用 any 类型
        '@typescript-eslint/no-non-null-assertion': 'off',
        '@typescript-eslint/no-namespace': 'off', // 禁止使用自定义 TypeScript 模块和命名空间。
        '@typescript-eslint/semi': 'off',

        // eslint-plugin-vue (https://eslint.vuejs.org/rules/)
        'vue/multi-word-component-names': 'off', // 要求组件名称始终为 “-” 链接的单词
        'vue/script-setup-uses-vars': 'error', // 防止<script setup>使用的变量<template>被标记为未使用
        'vue/no-mutating-props': 'off', // 不允许组件 prop的改变
        'vue/attribute-hyphenation': 'off', // 对模板中的自定义组件强制执行属性命名样式
    },
}

2.4 新建忽略文件

2.4.1 在项目根目录下,和.gitignore同级,创建.eslintignore文件

忽略dist以及node_modules即可

dist
node_modules

2.4.2 添加运行脚本

在packjson.json中script字段中添加俩行命令

"scripts": {
    "lint": "eslint src",
    "fix": "eslint src --fix"
}

三、配置prettier

eslint针对的是javascript,在eslint看来,语法对了就能保证代码正常运行,格式问题属于其次;而prettier属于格式化工具,所以它就把eslint没干好的事接着干。总结起来,eslint和prettier这俩兄弟一个保证js代码质量,一个保证代码美观。

3.1 安装prettier

pnpm install -D eslint-plugin-prettier prettier eslint-config-prettier

3.2 新建prettier配置文件

日常构建使用我提供的模版即可,想自行搭配或深入了解可以查看prettier官网完整配置

在根目录下新建.prettierrc.json文件

注解版

{
  "printWidth": 100,	//每行最多显示的字符数
  "tabWidth": 4,//tab的宽度 2个字符
  "useTabs": true,//使用tab代替空格
  "semi": true,//结尾使用分号
  "singleQuote": true,//使用单引号代替双引号
  "trailingComma": "none",//结尾是否添加逗号
  "bracketSpacing": true,//对象括号俩边是否用空格隔开
  "bracketSameLine": true,//组件最后的尖括号不另起一行
  "arrowParens": "always",//箭头函数参数始终添加括号
  "htmlWhitespaceSensitivity": "ignore",//html存在空格是不敏感的
  "vueIndentScriptAndStyle": false,//vue 的script和style的内容是否缩进
  "endOfLine": "auto",//行结尾形式 mac和linux是\n  windows是\r\n 
  "singleAttributePerLine": false //组件或者标签的属性是否控制一行只显示一个属性
}

开发版

{
    "printWidth": 100,
    "tabWidth": 4,
    "useTabs": true,
    "semi": true,
    "singleQuote": true,
    "trailingComma": "none",
    "bracketSpacing": true,
    "bracketSameLine": true,
    "arrowParens": "always",
    "htmlWhitespaceSensitivity": "ignore",
    "vueIndentScriptAndStyle": false,
    "endOfLine": "auto",
    "singleAttributePerLine": false
}

3.3 新建忽略文件

在根目录下新建.prettierignore文件

/dist/*
/html/*
.local
/node_modules/**
**/*.svg
**/*.sh
/public/*

3.4 添加脚本

在packjson.json中script字段中添加命令

"scripts": {
    "lint": "eslint src",
    "fix": "eslint src --fix",
    "format": "prettier --write \"./**/*.{html,vue,js,ts,json,md}\" "
}

四、配置stylelint

stylelint为css的lint工具。可格式化css代码,检查css语法错误与不合理的写法,指定css书写顺序等。

4.1 安装stylelint

我们的项目中使用scss作为预处理器,安装以下依赖:

pnpm add sass sass-loader stylelint postcss postcss-scss postcss-html stylelint-config-prettier stylelint-config-recess-order stylelint-config-recommended-scss stylelint-config-standard stylelint-config-standard-vue stylelint-scss stylelint-order stylelint-config-standard-scss -D

4.2 新建stylelint配置文件

在根目录下新建.stylelintrc.cjs文件

// @see https://stylelint.bootcss.com/

module.exports = {
    extends: [
        'stylelint-config-standard', // 配置stylelint拓展插件
        'stylelint-config-html/vue', // 配置 vue 中 template 样式格式化
        'stylelint-config-standard-scss', // 配置stylelint scss插件
        'stylelint-config-recommended-vue/scss', // 配置 vue 中 scss 样式格式化
        'stylelint-config-recess-order', // 配置stylelint css属性书写顺序插件,
        'stylelint-config-prettier', // 配置stylelint和prettier兼容
    ],
    overrides: [
        {
            files: ['**/*.(scss|css|vue|html)'],
            customSyntax: 'postcss-scss',
        },
        {
            files: ['**/*.(html|vue)'],
            customSyntax: 'postcss-html',
        },
    ],
    ignoreFiles: [
        '**/*.js',
        '**/*.jsx',
        '**/*.tsx',
        '**/*.ts',
        '**/*.json',
        '**/*.md',
        '**/*.yaml',
    ],
    /**
     * null  => 关闭该规则
     * always => 必须
     */
    rules: {
        'value-keyword-case': null, // 在 css 中使用 v-bind,不报错
        'no-descending-specificity': null, // 禁止在具有较高优先级的选择器后出现被其覆盖的较低优先级的选择器
        'function-url-quotes': 'always', // 要求或禁止 URL 的引号 "always(必须加上引号)"|"never(没有引号)"
        'no-empty-source': null, // 关闭禁止空源码
        'selector-class-pattern': null, // 关闭强制选择器类名的格式
        'property-no-unknown': null, // 禁止未知的属性(true 为不允许)
        'block-opening-brace-space-before': 'always', //大括号之前必须有一个空格或不能有空白符
        'value-no-vendor-prefix': null, // 关闭 属性值前缀 --webkit-box
        'property-no-vendor-prefix': null, // 关闭 属性前缀 -webkit-mask
        'selector-pseudo-class-no-unknown': [
            // 不允许未知的选择器
            true,
            {
                ignorePseudoClasses: ['global', 'v-deep', 'deep'], // 忽略属性,修改element默认样式的时候能使用到
            },
        ],
    },
}

4.3 新建忽略文件

在根目录下新建.stylelintignore文件

/node_modules/*
/dist/*
/html/*
/public/*

4.4 添加脚本

在packjson.json中script字段中添加命令

"scripts": {
    "lint": "eslint src",
    "fix": "eslint src --fix",
    "format": "prettier --write \"./**/*.{html,vue,js,ts,json,md}\" ",
    "lint:eslint": "eslint src/**/*.{ts,vue} --cache --fix",
    "lint:style": "stylelint src/**/*.{css,scss,vue} --cache --fix",
}

五、配置husky

在上面我们已经集成好了我们代码校验工具,但是需要每次手动的去执行命令才会格式化我们的代码。如果有人没有格式化就提交了远程仓库中,那这个规范就没什么用。所以我们需要强制让开发人员按照代码规范来提交。要做到这件事情,就需要利用husky在代码提交之前触发git hook(git在客户端的钩子),然后自动执行pnpm run format来自动的格式化我们的代码。

5.1 安装husky

pnpm install -D husky

5.2 生成husky配置文件

注意:要先在项目根目录下git init 不然会执行失败

npx husky-init

执行此命令后会在根目录下生成个一个.husky目录,在这个目录下面会有一个pre-commit文件,这个文件里面的命令在我们执行commit的时候就会执行

#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

pnpm run format

如此一来,即使我们忘了格式化代码就去提交,husky也会帮我们拦截commit,先进行格式化再去提交代码。

六、配置commitlint

对于我们的commit信息,也是有统一规范的,不能随便写,要让每个人都按照统一的标准来执行,我们可以利用commitlint来实现。

6.1 安装commitlint

pnpm add @commitlint/config-conventional @commitlint/cli -D

6.2 新建commitlint配置文件

在根目录下新建commitlint.config.cjs文件

module.exports = {
    extends: ['@commitlint/config-conventional'],
    // 校验规则
    rules: {
        'type-enum': [
            2,
            'always',
            [
                'feat',//新特性、新功能
                'fix',//修改bug
                'docs',//文档修改
                'style',//代码格式修改, 注意不是 css 修改
                'refactor',//代码重构
                'perf',//优化相关,比如提升性能、体验
                'test',//测试用例修改
                'chore',//其他修改, 比如改变构建流程、或者增加依赖库、工具等
                'revert',//回滚到上一个版本
                'build',//编译相关的修改,例如发布版本、对项目构建或者依赖的改动
            ],
        ],
        'type-case': [0],
        'type-empty': [0],
        'scope-empty': [0],
        'scope-case': [0],
        'subject-full-stop': [0, 'never'],
        'subject-case': [0, 'never'],
        'header-max-length': [0, 'always', 72],
    },
}

6.3 添加脚本

在packjson.json中script字段中添加命令

"scripts": {
    "lint": "eslint src",
    "fix": "eslint src --fix",
    "format": "prettier --write \"./**/*.{html,vue,js,ts,json,md}\" ",
    "lint:eslint": "eslint src/**/*.{ts,vue} --cache --fix",
    "lint:style": "stylelint src/**/*.{css,scss,vue} --cache --fix",
    "prepare": "husky install",
    "commitlint": "commitlint --config commitlint.config.cjs -e -V",
}

6.4 搭配husky来使用

npx husky add .husky/commit-msg 

6.5 配置husky文件

在生成的commit-msg文件中添加下面的命令

#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

pnpm commitlint

当我们 commit 提交信息时,就不能再随意写了,必须是 git commit -m 'fix: xxx’符合类型的才可以,需要注意的是类型的后面冒号需要用英文的并且冒号后面是需要空格的

七、统一包管理器

团队开发项目的时候,需要统一包管理器工具,因为不同包管理器工具下载同一个依赖,可能版本不一样,导致项目出现bug问题,因此包管理器工具需要统一管理!

7.1 新建配置文件

在根目录创建scripts/preinstall.js文件

if (!/pnpm/.test(process.env.npm_execpath || '')) {
    console.warn(
        `\u001b[33mThis repository must using pnpm as the package manager ` +
            ` for scripts to work properly.\u001b[39m\n`,
    )
    process.exit(1)
}

7.2 添加脚本

在packjson.json中script字段中添加命令

"scripts": {
    "lint": "eslint src",
    "fix": "eslint src --fix",
    "format": "prettier --write \"./**/*.{html,vue,js,ts,json,md}\" ",
    "lint:eslint": "eslint src/**/*.{ts,vue} --cache --fix",
    "lint:style": "stylelint src/**/*.{css,scss,vue} --cache --fix",
    "prepare": "husky install",
    "commitlint": "commitlint --config commitlint.config.cjs -e -V",
    "preinstall": "node ./scripts/preinstall.js"
}

当我们使用npm或者yarn来安装包的时候,就会报错了。原理就是在install的时候会触发preinstall(npm提供的生命周期钩子)这个文件里面的代码。

八、配置src别名

项目会经常引用src目录下的文件,频繁使用…/…/比较麻烦,配置一个别名直接从src/开始查找

8.1 配置viteconfig.ts文件

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import path from 'path' // 引入path模块

// https://vitejs.dev/config/
export default defineConfig({
	plugins: [vue()],
    // 配置src目录别名
    resolve: {
        alias: {
            "@": path.resolve("./src") // 相对路径别名配置,使用 @ 代替 src
        }
    }
});

8.2 配置tsconfig.json文件

compilerOptions中添加

{
    "compilerOptions": {
        /* 基地址 */
        "baseUrl": "./", // 解析非相对模块的基地址,默认是当前目录
        "paths": { //路径映射,相对于baseUrl
            "@/*": ["src/*"] 
        }
    }
}

九、配置环境变量

项目开发过程中,至少会经历开发环境测试环境生产环境三个阶段。不同阶段请求的状态(如接口地址等)不尽相同,若手动切换接口地址是相当繁琐且易出错的。于是环境变量配置的需求就应运而生,我们只需做简单的配置,把环境状态切换的工作交给代码。

9.1 新建环境文件

根目录下依次新建

  • 开发环境:.env.development
# 变量必须以 VITE_ 为前缀才能暴露给外部读取
NODE_ENV = 'development'
VITE_APP_TITLE = '小川工程化系统'
VITE_APP_BASE_API = '/dev-api'	
  • 生产环境:.env.production
# 变量必须以 VITE_ 为前缀才能暴露给外部读取
NODE_ENV = 'production'
VITE_APP_TITLE = '小川工程化系统'
VITE_APP_BASE_API = '/prod-api'	
  • 测试环境:.env.test
# 变量必须以 VITE_ 为前缀才能暴露给外部读取
NODE_ENV = 'test'
VITE_APP_TITLE = '小川工程化系统'
VITE_APP_BASE_API = '/test-api'

9.2 添加脚本

在packjson.json中script字段中添加命令

"scripts": {
    "dev": "vite",
    "build": "vue-tsc && vite build",
    "preview": "vite preview",
    "lint": "eslint src",
    "fix": "eslint src --fix",
    "format": "prettier --write \"./**/*.{html,vue,js,ts,json,md}\" ",
    "lint:eslint": "eslint src/**/*.{ts,vue} --cache --fix",
    "lint:style": "stylelint src/**/*.{css,scss,vue} --cache --fix",
    "prepare": "husky install",
    "commitlint": "commitlint --config commitlint.config.cjs -e -V",
    "preinstall": "node ./scripts/preinstall.js",
    "build:test": "vue-tsc && vite build --mode test",
    "build:pro": "vue-tsc && vite build --mode production"
},

通过import.meta.env获取环境变量

9.3 配置env TS 提示

在src/vite-env.d.ts 文件中

/// <reference types="vite/client" />

/** import.meta.env 类型声明 */
interface ImportMetaEnv {
    VITE_APP_TITLE:string
    VITE_APP_BASE_API: string
}

env_1.png

十、配置UI组件库

以Element Plus为例,按需引入

10.1 安装element-plus

pnpm install element-plus @element-plus/icons-vue

10.2 安装按需引入另外两个插件

pnpm install -D unplugin-vue-components unplugin-auto-import

10.3 tsconfig.json中添加如下代码

{
    "compilerOptions": {
        // ...
        "types": ["element-plus/global"]
    }
}

10.4 vite.config.ts配置如下

import { defineConfig } from 'vite'

/** 自动导入插件 */
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

export default defineConfig({
    // ...
    plugins: [
        // ...
        AutoImport({
            resolvers: [ElementPlusResolver()],
        }),
        Components({
            resolvers: [ElementPlusResolver()],
        })
    ],
})

10.5 国际化设为中文环境

在main.ts中添加如下代码

/** 引入element-plus */
import ElementPlus from 'element-plus'
//@ts-ignore忽略当前文件ts类型的检测否则有红色提示(打包会失败)
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'

const app = createApp(App);

app.use(ElementPlus, {
	locale: zhCn,
})

app.mount('#app');

在组件中使用 拥有良好的提示

element-plus_1.png

十一、配置SVG图标

在开发项目的时候经常会用到svg矢量图,而且我们使用SVG以后,页面上加载的不再是图片资源,这对页面性能来说是个很大的提升,而且我们SVG文件比img要小的很多,放在项目中几乎不占用资源。

11.1 安装svg插件

pnpm install vite-plugin-svg-icons -D 

11.2 在vite.config.ts中添加配置

import { defineConfig } from 'vite';
import path from 'path' // 引入path模块

/** 引入svg插件 */
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'

export default defineConfig({
    plugins: [
        ...
        createSvgIconsPlugin({
            iconDirs: [path.resolve(process.cwd(),'src/assets/icons')],
            symbolId: 'icon-[dir]-[name]',
        }),
    ],
 	...
});

注意:切记记得在src目录下新建assets目录,在assets目录下新建icons目录存放svg文件

11.3 在main.js中添加如下代码

/** 引入svg图标 */
import 'virtual:svg-icons-register';

11.4 封装SvgIcon.vue组件

在/src/components/SvgIcon/index.vue

<template>
    <!-- svg:图标外层容器节点,内部需要与use标签结合使用 -->
    <svg :style="{width, height}">
        <!-- xlink:href 执行用哪一个图标,属性值务必#icon-图标名字 -->
        <!-- use标签fill属性设置图标的颜色 -->
        <use :xlink:href="prefix + name" :fill="color"></use>
    </svg>
</template>

<script setup lang="ts">
type Props = {
    //xlink:href 属性值前缀
    prefix?: string
    // 图标名字
    name: string
    // 颜色
    color?: string,
    // 宽度
    width?: string,
    // 高度
    height?: string
}

withDefaults(defineProps<Props>(), {
    prefix: '#icon-',
    color: '#000',
    width: '16px',
    height: '16px'
})
</script>

11.5 自定义全局组件插件

在/src/components/index.ts

// 引入项目中全部的全局组件
import type { App,Component } from 'vue'
import SvgIcon from './SvgIcon/index.vue'

// 全局对象组件
const allGlobalComponent:{ [key: string]: Component } = {
    SvgIcon
}

// 对外暴露插件对象
export default {
    // 务必叫做install方法
    install(app: App) {
        // 注册项目中全部的全局组件
        Object.keys(allGlobalComponent).forEach(key => {
            app.component(key, allGlobalComponent[key])
        })
    }
}

11.6 在main.ts中注册插件

/** 引入自定义插件对象:注册整个项目全局全局组件 */
import globalComponent from '@/components'
//安装自定义插件
app.use(globalComponent);

11.7 使用svg图标

/src/assets/icons文件夹下,新建以.svg结尾的文件

svg_1.png

iconfont中复制svg代码,粘贴到react.svg文件中

svg_2.png

在组件中使用

svg_3.png

十二、配置Sass

在src目录下新建styles文件夹,中新建index.scss reset.scss variable.scss三个文件

12.1 清除默认样式

12.1.1 在reset.scss中

*,
*:after,
*:before {
    box-sizing: border-box;

    outline: none;
}

html,
body,
div,
span,
applet,
object,
iframe,
h1,
h2,
h3,
h4,
h5,
h6,
p,
blockquote,
pre,
a,
abbr,
acronym,
address,
big,
cite,
code,
del,
dfn,
em,
img,
ins,
kbd,
q,
s,
samp,
small,
strike,
strong,
sub,
sup,
tt,
var,
b,
u,
i,
center,
dl,
dt,
dd,
ol,
ul,
li,
fieldset,
form,
label,
legend,
table,
caption,
tbody,
tfoot,
thead,
tr,
th,
td,
article,
aside,
canvas,
details,
embed,
figure,
figcaption,
footer,
header,
hgroup,
menu,
nav,
output,
ruby,
section,
summary,
time,
mark,
audio,
video {
    font: inherit;
    font-size: 100%;

    margin: 0;
    padding: 0;

    vertical-align: baseline;

    border: 0;
}

article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
    display: block;
}

body {
    line-height: 1;
}

ol,
ul {
    list-style: none;
}

blockquote,
q {
    quotes: none;

    &:before,
    &:after {
        content: '';
        content: none;
    }
}

sub,
sup {
    font-size: 75%;
    line-height: 0;

    position: relative;

    vertical-align: baseline;
}

sup {
    top: -.5em;
}

sub {
    bottom: -.25em;
}

table {
    border-spacing: 0;
    border-collapse: collapse;
}

input,
textarea,
button {
    font-family: inhert;
    font-size: inherit;

    color: inherit;
}

select {
    text-indent: .01px;
    text-overflow: '';

    border: 0;
    border-radius: 0;

    -webkit-appearance: none;
    -moz-appearance: none;
}

select::-ms-expand {
    display: none;
}

code,
pre {
    font-family: monospace, monospace;
    font-size: 1em;
}

12.1.2 index.scss文件中使用

// 引入清除默认样式文件
@import './reset.scss';

12.2 配置全局变量

配置的目的是在任意组件直接使用scss变量,而不需要引入variable.scss文件

在vite.config.ts中添加如下代码

export default defineConfig((config) => {
    css: {
        preprocessorOptions: {
            scss: {
                javascriptEnabled: true,
                    additionalData: '@import "./src/styles/variable.scss";',
            },
        },
    },
}

注意:@import "./src/styles/variable.scss";后面的;不要忘记,不然会报错!

十三、二次封装axios

13.1 安装axios

pnpm install axios nprogress
pnpm i --save-dev @types/nprogress

13.2 新建文件

在src目录下新建utils文件夹,再新建request.ts文件

import axios from "axios";
import Nprogress from 'nprogress';
import 'nprogress/nprogress.css'; // 导入样式,否则看不到效果
import { ElMessage } from "element-plus";
//创建axios实例
let request = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 10000
})
//请求拦截器
// 添加请求拦截器
request.interceptors.request.use(
    function (config) {
        // 在发送请求之前做些什么
        Nprogress.start();
        return config;
    },
    function (error) {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
);

//响应拦截器
request.interceptors.response.use((response) => {
    return response.data;
}, (error) => {
    //处理网络错误
    let msg = '';
    let status = error.response.status;
    switch (status) {
        case 401:
            msg = "token过期";
            break;
        case 403:
            msg = '无权访问';
            break;
        case 404:
            msg = "请求地址错误";
            break;
        case 500:
            msg = "服务器出现问题";
            break;
        default:
            msg = "无网络";

    }
    ElMessage({
        type: 'error',
        message: msg
    })
    return Promise.reject(error);
});
export default request;

十四、API接口统一管理

14.1 新建文件

在开发项目的时候,接口可能很多需要统一管理。在src目录下去创建api文件夹去统一管理项目的接口;

在api文件夹下分别新建index.ts type.ts login.ts文件

14.2 type.ts

export interface LoginFormData {
    username: string;
    password: string;
}

export interface User {
    id: number;
    username: string;
    email: string;
    phone: string;
    avatar: string;
    introduction: string;
    roles: string[];
    permissions: string[];
    createTime: string;
    updateTime: string;
    lastLoginTime: string;
    status: number;
}

export interface LoginResponseData {
    token: string;
    user: User;
}

14.3 login.ts

import request from "@/utils/request";

import type { LoginFormData,LoginResponseData } from './type'


enum API {
    LOGIN_URL = '/admin/acl/index/login',
}

// 登录接口
export const reqLogin = (data: LoginFormData) => 
    request.post<any, LoginResponseData>(API.LOGIN_URL,data)

14.4 index.ts

export { reqLogin } from './login'

十五、附Gitee源码

https://gitee.com/cwk985/v3_ts_template.git