vite+vue3+Ts builds the basic project framework

Preface

As front-end technology is updated, programmers' technology stacks must keep up. Originally, they wanted to lie down, but unexpectedly they were pushed away.

Last month, the development team received a new project requirement, requiring the development technology stack vue2 to be replaced with vue3. The unprepared editor was confused, huh? Why do you say just change it? No advance notice and no time to study, just get started? That’s outrageous 0.0!

image.png
I had no choice but to develop together with my colleagues who knew Vue3, and developed the module with reference to the modules written by my colleagues. It turned out that except for some writing methods that were different, others were almost the same. After I realized this, I stopped panicking and just learned while doing it. development. After the project development was completed, I deliberately took some time to understand what preparations were needed from starting the project from scratch to entering development. Because the project started as a framework built by colleagues, I only needed to write a page to participate, so this time it passed Ask your colleagues and figure it out on your own to come up with a set of the most basic frameworks, which will be used in most projects.

Vue3 project basic framework construction process

Some relevant official documents

vite official Chinese documentation

TypeScript Chinese Manual

1. Create a project

First use vite to initialize the project, then select vue+typeScript during the initialization process

npm init vite

2. Install dependencies

It should be noted that the above way of creating a project is different from the traditional way. It will not automatically install dependencies, that is, there is no node_modules package. We need to manually install the dependencies ourselves. This is why using vite to create a project is very fast. reason, so we need to npm iinstall dependencies using

npm i

After initializing the dependencies, install the basic dependencies vue-router, vuex, and axios that are often used in project development.

npm i -save vue-router vuex axios

Install the dependencies required for development. I often use less. If you are used to using sass, you can replace it.

npm i -D less less-loader

3.ts global configuration

Add configuration, global type, and interface in tsconfig.json. This is the file that needs to be compiled in the configuration project

"include": [
    "src/**/*.ts",
    "src/**/*.d.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "types/**/*.d.ts",
    "types/**/*.ts"
],

4. Configure project path alias

Add configuration in tsconfig.json to handle ts compilation error when importing files through "@/"

"compilerOptions": {
    
    
...
"baseUrl": "./",
    "paths": {
    
    
      "@/*": [
        "src/*"
      ],
      "#/*": [
        "types/*"
      ]
    }
}

Add configuration in vite.config.ts to handle the problem of running errors when importing files through "@/"

// 引入path时会标红,需要安装响应的type依赖 npm i @types/node
import * as path from 'path'
// 或 const path = require('path')
export default ({
    
     mode }) => {
    
    
  return defineConfig({
    
    
      resolve: {
    
    
          alias: {
    
    
              '@': path.join(__dirname, 'src'),
              '#': path.join(__dirname, 'types'); 
          }
      },
  })
}

5. Create page folders

Create a views folder under the src folder, and download it to create the home/index.vue file. There are no views when creating a project, so you need to create them yourself. Of course, you can also name other semantic folders such as pages.

<template>
  <div>首页</div>
</template>
<script lang='ts' setup>
import {
      
       reactive, ref, toRefs } from 'vue'
</script>
<style scoped lang="less">
</style>

6. Configure routing

Create the router folder under the src folder, and create the index.ts file under it. Some configuration items used to manage routing

//index.ts
import {
    
     createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router"
const routers = [
  {
    
    
    path: '/',
    name: 'home',
    component: () => import('@/views/home/index.vue'),
  },
];const router = createRouter({
    
    
  history: createWebHashHistory(),
  routes: routers as unknown as RouteRecordRaw[]
})// 路由守卫
router.beforeEach((to, from, next) => {
    
    
  next()
})export default router;

Introduce and use in main.ts file. Here is a reminder that app.use(router) needs to be written in front of app.mount('#app'). The problem is that the router needs to be installed first before the app can be mounted to the '#pp' tag, otherwise the router cannot be used.

import {
    
     createApp } from 'vue'
import App from './App.vue'
const app = createApp(App);import router from './router'
// 初始化路由
app.use(router)
app.mount('#app')

If the above app.use(router) is written after app.mount('#app'), then using it here will have no effect because it is a component in the router.

The APP.vue file uses the router-view component.

<template>
  <router-view />
</template>
<script lang='ts' setup>
</script>
<style scoped lang="less">
</style>

7. Configure vuex

Create a store folder under the src folder and create an index.ts file under it.

//index.ts
import {
    
     createStore } from 'vuex'
export const store = createStore({
    
    
  state() {
    
    
    return {
    
    }
  },
  getters: {
    
    },
  mutations: {
    
    },
  actions: {
    
    },
  modules: {
    
    }
})

Introduced in main.ts file

...
// 初始化vuex
import store from './store'
app.use(store)

8. Encapsulate the axios request interface and configure the request interceptor

Create an api folder under the src folder, and create index.ts and request.ts files under it.

1. Configure the request interceptor in the request.ts file

// request.ts
import axios, {
    
     AxiosRequestConfig, AxiosResponse } from "axios";
const service = axios.create({
    
    
  timeout: 60000,
  baseURL: ''
})// 请求失败回调函数处理
const error = (error: {
    
     request: AxiosRequestConfig, response: AxiosResponse }) => {
    
    
  if (error.response.status === 401) {
    
    
    // 登录状态过期或未登录
  }
  return Promise.reject(error)
}// 请求前
service.interceptors.request.use((request: AxiosRequestConfig) => {
    
    
  return request
}, error)// 响应后
service.interceptors.response.use((response: AxiosResponse) => {
    
    
  return response
}, error)export {
    
     service as axios }

2. Create the interface folder under the src folder, create the request.ts file under it, and configure the type required for the request interface.

// request.ts
/** 普通数据响应 */
export interface ResDataStruct<T = any> {
    
    
  /** 响应内容体 */
  data: T,
  /** api响应信息 */
  message: string,
  /** api响应编码 */
  code: number,
  /** api接口返回是否成功 */
  success: boolean,
  /** api接口查询数据库总数 */
  total: number | string | null,
}

3. Encapsulate the axios request in the index.ts file. There are many ways to encapsulate axios requests. Here I use the method of creating object instances to encapsulate. I think this is more convenient to manage. If you have a better packaging method, you can leave a comment below.

// index.ts
import {
    
     ResDataStruct } from "@/interface/request";
import {
    
     axios } from "@/utils/request"
export const httpApi = new class {
    
    
    constructor() {
    
    
        // 请求接口路径
        this.loginApi = '/login/login' // 登录
    }
    Login( data: Object)){
    
    
        return axios<ResDataStruct<T>>({
    
     url: this.loginApi, method: "post", data })
    }
}

9. Create a global configuration file

Create some additional configuration folders under the src folder, and create the index.ts file under the corresponding folder. like:

  • hooks (configuration of global shared functions)
  • interface (define global interface type)
  • types (define global type aliases)

Of course, these configurations here are just to make it easier to manage data. I like to distinguish them clearly, so that they will be easier to maintain in subsequent iterations.

10. Extension

The basic framework can be built here. Here are some extension plug-ins. You can add them yourself if you need to, but I think they should be needed for most projects.

1. The function of the vite plug-in @vitejs/plugin-legacy is to provide traditional browser compatibility support for packaged files.

// npm 安装依赖
npm i -save @vitejs/plugin-legacy
​
// vite.config.ts
import legacy from '@vitejs/plugin-legacy'
export default defineConfig({
    
    
    plugins: [
        legacy({
    
    
            targets: ['defaults', 'not IE 11'],
            additionalLegacyPolyfills: ['regenerator-runtime/runtime']
        }),
        ...
    ],
})

2. The function of the vite plug-in vite-plugin-compression is to perform gzip compression, an vite-plugin-compressenhanced version.

// npm 安装依赖
npm i -save vite-plugin-compression
​
// vite.config.ts
import viteCompression from 'vite-plugin-compression'
export default defineConfig({
    
    
    plugins: [
        viteCompression(),
        ...
    ],
})

3. The role of the vite plug-in vite-plugin-rsw - a webAssembly plug-in implemented based on vite, supports hot updates, and friendly error prompts

// npm 安装依赖
npm i -save vite-plugin-rsw

4. The function of the vite plug-in @vitejs/plugin-vue-jsx is to compile JSX files

// npm 安装依赖
npm i -save @vitejs/plugin-vue-jsx
​
// vite.config.ts
import vueJsx from '@vitejs/plugin-vue-jsx'
export default defineConfig({
    
    
    plugins: [
        vueJsx(),
        ...
    ],
})

That’s all for the specifics. If you have any questions or questions, please leave a message below or send a private message. If it is useful to you, please like and save it. Thank you for your support!

Guess you like

Origin blog.csdn.net/qingshui_zhuo/article/details/131193113