创建react+ts项目

// 固定写法,可单独创建    名字          模板      react+ts
npm create vite@latest react_ts -- --template react-ts

安装Ant Design Mobile移动端组件库

npm install --save antd-mobile

//使用 直接引入即可
import { Button } from 'antd-mobile'

安装路由

npm i react-router-dom
import { RouteObject, createBrowserRouter } from "react-router-dom";
import Device from "@/components/Device";
import Home from "@/components/Home";
const routers: RouteObject[] = [
  {
    path: "/",
    element: <Home />
  }, {
    path: "Device",
    element: <Device />
  }
]
const router = createBrowserRouter(routers)
export {
  router
}
// import React from 'react'
import ReactDOM from 'react-dom/client'
import './index.css'
import { RouterProvider } from "react-router-dom";
import { router } from "./router/index.tsx";
ReactDOM.createRoot(document.getElementById('root')!).render(
  // <React.StrictMode>
  <RouterProvider router={router} />
  // </React.StrictMode>,
)

配置@别名

  • 安装node,ts不支持node,所以要安装插件配置
npm i @types/node -D
  • vite.config.ts 加入resolve配置
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// 需要安装@types/node
import path from 'path'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  // 别名配置
  resolve:{
    alias:{
      "@":path.resolve(__dirname,"./src")
    }
  }
})
  • tsconfig.json 加入compilerOptions下的配置,别名就配置成功了
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
  },
  "include": ["src"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

安装aixos

npm i axios -D

配置

请求拦截配置token头部,响应拦截处理数据传递

import axios from "axios";

const httpInstance = axios.create({
  baseURL:"http://localhost:8081",
  timeout:5000
})

// 请求拦截器
httpInstance.interceptors.request.use(
  (response)=>{
    const res =response
    return res
  },
  (error)=>{
    return Promise.reject(error)
  }
)

// 响应拦截器
httpInstance.interceptors.response.use(
  (response)=>{
    const res =response
    return res
  },
  (error)=>{
    return Promise.reject(error)
  }
)

export {
  httpInstance as http
}

封装

/src/api/index.ts

import { http } from "@/utils/http";

// 定义泛型
type ResType<T> = {
  code:number
  massage:string
  data:T
}

// 定义接口类型
export  type ChannelItem = {
  key:string
  title:string,
  List:{title:string}[]
}

// 
type ChannelRes ={
  list:ChannelItem[]
}

export const fetchChannelAPI = ()=>{
  return http.request<ResType<ChannelRes>>({
    url:"/data"
  })
}
03-31 10:12