dva

安装项目

dva new 项目名称

构建项目环境

1、构建TS环境

安装依赖包

yarn add @types/react @types/react-dom ts-loader ts-lint

初始化,生成tsconfig.json

tsc --init

tsconfig.json文件配置

{
  "compilerOptions": {
      "strictNullChecks": true,
      "moduleResolution": "node",
      "allowSyntheticDefaultImports": true,
      "experimentalDecorators": true,
      "jsx": "preserve",
      "noUnusedParameters": true,
      "noUnusedLocals": true,
      "target": "es6",
      "rootDir": "./src",
      "lib": [
          "dom", 
          "es7"
      ]
  },
  "exclude": [
      "node_modules",
      "lib",
      "es"
  ]
}

创建tslint.json,进行配置

{
  "extends": [
      "tslint:latest",
      "tslint-react"
  ],
  "linterOptions": {
      "exclude": [
          "node_modules/**/*.ts",
          "src/**/*.{ts,tsx}"
      ]
  },
  "rules": {
      "object-literal-sort-keys": false,
      "jsx-no-lambda": false,
      "eofline": false,
      "no-consecutive-blank-lines": false,
      "no-var-requires": false,
      "quotemark": false,
      "space-within-parents": false,
      "no-submodule-imports": false,
      "no-implicit-dependencies": false,
      "ordered-imports": [ false ],
      "jsx-boolean-value": false,
      "no-trailing-whitespace": false,
      "semicolon": false,
      "trailing-comma": false,
      "space-in-parents": false,
      "typedef-whitespace": [ false ],
      "whitespace": [ true ],
      "interface-over-type-literal": true,
      "no-duplicate-imports": false,
      "no-namespace": true,
      "no-internal-module": true
  }
}
  • 注:在启动项目时报错tslint-react只需要主动安装tslint-react即可:
yarn add tslint-react

2、组件库配置

安装依赖包

 yarn add antd babel-plugin-import -S

编辑 .Webpackrc,使 babel-plugin-import (按需加载)插件生效。

{
  "extraBabelPlugins": [
    ["import", {
      "libraryName": "antd",
      "libraryDirectory": "lib",
      "style": "css"
    }]
  ]
}

3、将hash路由改成history模式

import {createBrowserHistory} from 'history'

const customHistory = createBrowserHistory();
// 1. Initialize
const app = dva({
  history: customHistory,
});

4、roadhog

  • https://github.com/sorrycc/roadhog

将.webpackrc改成js文件

要将内容暴露,module.exports={}

alias配置

 "alias":{
    "@":path.join(__dirname,'./src'),
    "assets": path.join(__dirname,'./src/assets'),
    ...
    ...
  }

proxy配置

"proxy":{
      "/index.php":{
          "target":"http://qinqin.net",
          "changeOrigin":true
      }
  }

css模块化

 "disableCSSModules": true

5、dva中进行mock数据

配置.roadhogrc.mock.js 文件

export default {
  "GET /api/user": {
    userInfo: '普通用户',
    username: 'lakers'
  }
};

项目(第三方网站)

https://www.fastmock.site/#/projects

6、ts引入

定义接口

// cookie操作函数的接口定义
export interface JsonObj{
  [propsName: string]: any
}

export interface GetCookie {
  (name:string):( Array<string> | Array<JsonObj>)
}
export interface SetCookie {
  (name:string,value:string,days: (number|string)): void
}

// 对 request 来进行类型的定义
export interface RequestOptions {
    url: string,
    method?: string,
    params?: JsonObj,
    data?: JsonObj,
    headers?: JsonObj,
    fetchType?: string
}
export interface Request<T> {
  (options: RequestOptions): Promise<T>
}

cookie.ts

import {GetCookie,SetCookie} from 'IF'

export const setCookie:SetCookie = function (name, value, days) {
  let d = new Date();
  d.setDate(d.getDate() + days)
  document.cookie = `${name}=${encodeURIComponent(value)};expires=${d};path=/`;
}


export const getCookie:GetCookie = function (name) {
  let arr = decodeURIComponent(document.cookie).split('; ');
  for (let i = 0; i < arr.length; i++) {
      let newarr = arr[i].split('=');
      if (name === newarr[0]) {
          return newarr[1];
      }
  }
}

request.ts

// axios + fetch 
import axios, { AxiosInstance, AxiosError, AxiosRequestConfig, AxiosPromise, AxiosResponse } from 'axios'
import { baseURL } from '../env';
import {Request} from '../interface'
// import fetchJsonp from 'fetch-jsonp'
// 创建自定义请求实例
const ins:AxiosInstance = axios.create({
  // baseURL,
  timeout: 4000 
})

// 拦截器

ins.interceptors.request.use(function (config: AxiosRequestConfig) :AxiosRequestConfig {
  return config
},function (error: AxiosError):AxiosPromise {
  return Promise.reject(error)
})
ins.interceptors.response.use(function (res: AxiosResponse): AxiosResponse  {
  return res
},function (error: AxiosError):AxiosPromise {
  return Promise.reject(error)
})

const request:Request<any> = options => {
  const {url,method="get",fetchType="CORS",params,headers={
    'Content-Type': 'application/x-www-form-urlencoded'
  },data} =options
     jsonp在ts中无法使用
  // if (fetchType != 'CORS'){
  //   // 我们用的是jsonp处理请求
  //   return new Promise((resolve,reject) => {
  //     fetchJsonp(url)
  //     .then(function(response) {
  //       return response.json()
  //     }).then(function(json) {
  //       resolve(json)
  //     }).catch(function(ex) {
  //       reject(ex)
  //     })
  //   })
  // }
  switch (method.toUpperCase()) {
    case 'GET':
      return ins.get(url,{params})
      break;
    case 'POST':
      switch (headers['Content-Type']) {
        case 'application/x-www-form-urlencoded':
          const p = new URLSearchParams()
          for(let key in data){
            p.append(key,data[key])
          }
          return ins.post(url,p,{headers})
          break;
        case 'multipart/form-data':
          const param = new FormData()
          for(let key in data){
            param.append(key,data[key])
          }
          return ins.post(url,param,{headers})
          break;
      
        default:
          return ins.post(url,data,{headers})
          break;
      }
      break;
    case 'PUT':
      return ins.put(url,data)
      break;
    case 'DELETE':
      return ins.delete(url,{data})
      break;
    case 'PATCH':
      return ins.patch(url,data)
      break;
    default:
      return ins.get(url,{params})
      break;
  }
}

export default request
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值