vite + vue3 + ts

项目初始化

// 使用 Vite 创建项目
npm init @vitejs/app XXX

选择 Vue + TS后,

cd XXX
npm install
npm run dev

一般到这一步,项目就已经初始化成功了。
但是也可能会在 npm run dev 的过程中报错,如下

XXX/node_modules/esbuild/bin/esbuild:2
throw new Error(`esbuild: Failed to install correctly
^

Error: esbuild: Failed to install correctly

Make sure you don't have "ignore-scripts" set to true. You can check this with
"npm config get ignore-scripts". If that returns true you can reset it back to
false using "npm config set ignore-scripts false" and then reinstall esbuild.

If you're using npm v7, make sure your package-lock.json file contains either
"lockfileVersion": 1 or the code "hasInstallScript": true. If it doesn't have
either of those, then it is likely the case that a known bug in npm v7 has
corrupted your package-lock.json file. Regenerating your package-lock.json file
should fix this issue.

从报错信息看,先查看 npm config get ignore-scripts 返回是否是false,否,则执行

npm config set ignore-scripts false

然后可以看的出来,报错的文件是 node_modules/esbuild,那再装一次呗~

node node_modules/esbuild/install.js

默认构建好的目录结构是不包含router和vuex的,手动安装:

npm install vue-router@next vuex@next -S

注:Vue3.0 只支持 Router 和 Vuex 4.0及以上版本

项目目录如下,仅供参考:


目录.jpg

配置别名

默认构建的是没有别名配置的,配置如下

import { defineConfig } from 'vite'
import { resolve } from 'path'

// https://vitejs.dev/config/
export default defineConfig({
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src')
    }
  }
})

然后 TS 就会报错:


dir-error.jpg

需要安装:

npm install @types/node -D

引入 element-plus

如果要使用 element ui 库,需要安装支持 Vue 3.0 的 element-plus 库

eslint prettier eslint-config-prettier eslint-plugin-prettier eslint-plugin-vue @type-eslint/parser @typescript-eslint/eslint-plugin

  1. 配置element-plus.ts
// plugins/element-plus.ts
import { App } from 'vue'
import ElementPlus from 'element-plus'
import * as icons from '@element-plus/icons-vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'

export default {
  install (app: App) {
    // element-plus 图标
    let k: keyof typeof icons
    for (k in icons) {
      app.component(k, icons[k])
    }

    // element-plus 组件
    app.use(ElementPlus, {
      locale: zhCn
    })
  }
}
  1. main.ts中使用
import { createApp } from 'vue'
import ElementPlus from '@/plugins/element-plus'

const app = createApp(App)
  .use(ElementPlus)

封装request

  1. 配置环境变量
// env.ts
export function matchOrigin() {
  const hostname = location.hostname
  if (/-dev\./i.test(hostname)) {
    return '//dev-xxx.com'
  } else if (/-test\./.test(hostname)) {
    return '//sit-xxx.com'
  } else if (/-uat\./.test(hostname)) {
    return '//uat-xxx.com'
  } else {
    return '//xxx.com'
  }
}

export function matchBaseURL() {
  return `${calcOrigin()}/api`
}

  1. 全局loading封装
/**
* 全局loading效果:合并请求 避免重复请求
* 当调用一次showLoading,则次数+1;当次数为0时,即仅第一次发请求时显示loading
* 当调用一次hideLoading,则次数-1; 当次数为0时,即仅最后一次发请求时关闭loading
*/
import { ElLoading } from 'element-plus'
import { LoadingInstance } from 'element-plus/lib//components/loading/src/loading'

// 请求次数:用来记录当前页面总共请求的次数
let loadingRequestCount = 0

// 初始化loading
let loadingInstance: LoadingInstance

// showLoading 请求次数 ++
const showLoading = (target: object) => {
 if (loadingRequestCount === 0) {
   loadingInstance = ElLoading.service(target)
 }
 loadingRequestCount++
}

// hideLoading 请求次数 --
const hideLoading = () => {
 if (loadingRequestCount <= 0) return
 loadingRequestCount--
 if (loadingRequestCount === 0) {
   loadingInstance.close()
 }
}

export {
 showLoading,
 hideLoading
}

  1. request封装
/**
 * 请求封装 request.ts
 */
import axios, { AxiosInstance, AxiosPromise, AxiosRequestConfig, AxiosResponse } from 'axios'
import { matchBaseURL} from './env'
import { showLoading, hideLoading } from './loading'
const insts: Record<string, AxiosInstance> = {}

// 仅在构建请求实例时才执行 matchBaseURL
function init(baseURL?: string) {
  const key = baseURL || '_BASE_URL_'

  if (insts[key]) { return insts[key] }

  const inst = axios.create({
    baseURL: baseURL || matchBaseURL(),
    headers: {
      ...
    }
  })

  // 可在此处做一些请求拦截
  decorateService(inst)

  insts[key] = inst

  return inst
}

function decorateService(service: AxiosInstance) {
  service.interceptors.request.use(config => {
    showLoading({
      lock: true,
      text: 'Loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    // 每次请求前,插入token,待封装...
    const token = xxx()
    if (token) {
      config.headers!.Authorization = token
    }

    return config
  })

  service.interceptors.response.use(
    (response) => {
      setTimeout(() => {
        hideLoading()
      }, 200)
      const responseData = response.data
      // console.log('response', response)
      if (responseData.code === 200) {
        // 不能 resolve responseData,因为这里的类型为:AxiosResponse
        return Promise.resolve(response)
      }
      return Promise.reject(responseData)
    },
    (error) => {
      setTimeout(() => {
        hideLoading()
      }, 200)
      console.log('error', error)
      return Promise.reject(new Error('error'))
    }
  )
}

interface IRequest {
  <T = any, D = any>(url: string, config?: AxiosRequestConfig): AxiosPromise;
  <T = any, D = any>(config: AxiosRequestConfig): AxiosPromise;
}
const request: IRequest = function request<T = any, D = any>(url: string | AxiosRequestConfig, config?: AxiosRequestConfig): AxiosPromise {
  if (typeof url !== 'string') {
    config = url as AxiosRequestConfig
    url = config.url!
  } else {
    config || (config = {})
    config.url = url
  }

  // 按需实例化和复用
  const inst = init(config?.baseURL)

  // 发送请求
  return inst.request<T, AxiosResponse<T>, D>(config)
}

export function get<T = any, D = any>(url: string, params?: D, config?: AxiosRequestConfig<D>) {
  return request<T, D>({ ...(config || {}), params, url })
}

export function post<T = any, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>) {
  return request<T, D>({ ...(config || {}), data, url, method: 'POST' })
}

export { get as $get, post as $post }

export default request

相关库:
flow:
vueflow
x6.antv

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,386评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,142评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,704评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,702评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,716评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,573评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,314评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,230评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,680评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,873评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,991评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,706评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,329评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,910评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,038评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,158评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,941评论 2 355

推荐阅读更多精彩内容