Vue 3 + TypeScript 项目从零搭建模板
每次新项目都要配一遍环境,不如整理一个标准模板,直接复制粘贴。
初始化
1 2 3
| pnpm create vite my-project --template vue-ts cd my-project pnpm install
|
项目结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| src/ ├── api/ │ ├── index.ts │ └── modules/ ├── assets/ ├── components/ ├── composables/ ├── hooks/ ├── router/ │ └── index.ts ├── stores/ ├── styles/ ├── types/ ├── utils/ ├── views/ ├── App.vue └── main.ts
|
Axios 封装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| import axios from 'axios'
const instance = axios.create({ baseURL: import.meta.env.VITE_API_BASE, timeout: 15000, })
instance.interceptors.request.use((config) => { const token = localStorage.getItem('token') if (token) { config.headers.Authorization = `Bearer ${token}` } return config })
instance.interceptors.response.use( (res) => res.data, (err) => { if (err.response?.status === 401) { localStorage.removeItem('token') window.location.href = '/login' } return Promise.reject(err) } )
export default instance
|
路由配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({ history: createWebHistory(), routes: [ { path: '/', component: () => import('@/layouts/DefaultLayout.vue'), children: [ { path: '', name: 'Home', component: () => import('@/views/Home.vue') }, { path: 'about', name: 'About', component: () => import('@/views/About.vue') }, ], }, ], })
export default router
|
ESLint + Prettier
1
| pnpm add -D @antfu/eslint-config
|
1 2 3 4 5 6 7
| import antfu from '@antfu/eslint-config'
export default antfu({ typescript: true, vue: true, })
|
@antfu/eslint-config 一套搞定 ESLint + Prettier,不用分开配。
环境变量
1 2 3 4 5
| VITE_API_BASE=http://localhost:3000/api
VITE_API_BASE=https://api.example.com/api
|
1 2 3 4 5 6 7 8 9
|
interface ImportMetaEnv { readonly VITE_API_BASE: string }
interface ImportMeta { readonly env: ImportMetaEnv }
|
一键启动
1 2 3
| pnpm dev pnpm build pnpm preview
|
这套模板用了十几次了,够用。