前言

Vite、Vue3、TypeScript 已经成为 2026 年前端工程化的”标配三件套”。但很多团队在搭建项目时仍然停留在 npm create vite 后直接写业务的阶段,忽略了目录规范、路径别名、自动导入、代码规范、环境变量这些”看不见但天天用”的工程化配置。

本文将从一行命令开始,搭建一个具备完整工程化能力的 Vite + Vue3 + TypeScript 项目骨架。读完你将获得一份可以直接复用的项目模板,后续的 Composition API、Pinia、类型进阶文章都会基于这套骨架展开。

一、技术选型与前置准备

为什么是 Vite + Vue3 + TypeScript

  • Vite:开发阶段基于原生 ESM,冷启动几乎瞬间完成;生产环境用 Rollup 打包,产物质量有保障。
  • Vue3:Composition API 让逻辑复用更彻底,配合 <script setup> 写法极其简洁,性能也全面优于 Vue2。
  • TypeScript:类型系统把大量低级错误挡在编译期,配合 IDE 的智能提示,重构和协作成本显著降低。

三者结合后,开发体验、可维护性、性能三者兼得,这也是社区主流方案的方向。

环境要求

  • Node.js ≥ 18.12(Vite 5 要求 18+)
  • pnpm(推荐,磁盘占用和安装速度都优于 npm)
1
2
node -v   # 确认版本
npm i -g pnpm

二、使用 create-vue 脚手架初始化

官方的 create-vue 是目前最推荐的脚手架,它会一次性把 Vue3 + TS + ESLint + Router 等集成好。

1
pnpm create vue@latest my-app

命令会以交互方式询问要引入哪些特性,建议这样选择:

1
2
3
4
5
6
7
8
✔ Add TypeScript?                       … Yes
✔ Add JSX Support? … No
✔ Add Vue Router for Single Page App? … Yes
✔ Add Pinia for state management? … Yes
✔ Add Vitest for Unit testing? … No(按需)
✔ Add an End-to-End testing solution? … No(按需)
✔ Add ESLint for code quality? … Yes
✔ Add Prettier for code formatting? … Yes

初始化完成后:

1
2
3
cd my-app
pnpm install
pnpm dev # 启动开发服务器

浏览器打开 http://localhost:5173 即可看到默认页面。

三、目录结构规范

create-vue 生成的目录比较扁平,随着业务增长建议调整为如下分层结构:

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
src/
├── api/ # 接口请求封装与各业务模块 API
│ ├── request.ts # axios 实例与拦截器
│ └── user.ts
├── assets/ # 静态资源(图片、字体)
├── components/ # 全局通用组件
│ └── BaseButton.vue
├── composables/ # 可复用逻辑(Composition API 抽出来的 hooks)
│ └── useTheme.ts
├── directives/ # 自定义指令
├── layouts/ # 布局组件
│ └── DefaultLayout.vue
├── router/ # 路由
│ └── index.ts
├── stores/ # Pinia store
│ └── user.ts
├── styles/ # 全局样式、变量、mixin
│ ├── variables.scss
│ └── reset.scss
├── types/ # TS 类型定义(接口、枚举、业务类型)
│ └── user.d.ts
├── utils/ # 工具函数
│ └── format.ts
├── views/ # 页面级组件
│ └── HomeView.vue
├── App.vue
└── main.ts

约定:

  • components 放”通用组件”,views 放”页面组件”,路由只引用 views。
  • composables 放被多处复用的逻辑,命名以 use 开头。
  • types 集中放业务类型,避免散落在各 .vue 文件里。

四、路径别名配置

默认只能用相对路径,文件层级深时会出现 ../../../utils/format 这种”地狱路径”。配置 @ 指向 src 后,可以写成 @/utils/format。

修改 vite.config.ts

1
2
3
4
5
6
7
8
9
10
import { fileURLToPath, URL } from 'node:url'

export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
},
},
})

同步 tsconfig.json

TS 不认识 @ 会在编辑器报红,需要在 tsconfig.app.json 的 compilerOptions 里加上:

1
2
3
4
5
6
7
8
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}
}

两边都配置后,IDE 跳转、类型检查、打包都能正确解析 @。

五、环境变量

Vite 默认只暴露以 VITE_ 开头的变量给前端,通过 import.meta.env 访问。

创建多环境文件

1
2
3
.env                # 所有环境公共
.env.development # pnpm dev 时生效
.env.production # pnpm build 时生效
1
2
3
4
5
6
7
# .env.development
VITE_API_BASE_URL = /api
VITE_APP_TITLE = 我的实验室(dev)

# .env.production
VITE_API_BASE_URL = https://api.example.com
VITE_APP_TITLE = 我的实验室

代码里读取:

1
const baseUrl = import.meta.env.VITE_API_BASE_URL

为环境变量补充类型

在 src/env.d.ts 增强类型,避免写错变量名:

1
2
3
4
5
6
7
8
9
10
/// <reference types="vite/client" />

interface ImportMetaEnv {
readonly VITE_API_BASE_URL: string
readonly VITE_APP_TITLE: string
}

interface ImportMeta {
readonly env: ImportMetaEnv
}

加上后,import.meta.env.VITE_API_BASE_URL 会有完整类型提示,拼错变量名会直接报红。

六、ESLint + Prettier + EditorConfig

create-vue 已经选装了 ESLint 和 Prettier,但还需要做一些调优,让”保存即格式化”的体验顺畅。

.editorconfig 统一编辑器行为

在项目根目录新建 .editorconfig:

1
2
3
4
5
6
7
8
9
10
11
12
root = true

[*]
charset = utf-8
end_of_line = lf
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
trim_trailing_whitespace = false

eslint.config.js 关键规则

create-vue 默认用扁平配置(Flat Config),常用规则可补充如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import vueTsEslintConfig from '@vue/eslint-config-typescript'
import skipFormatting from '@vue/eslint-config-prettier/skip-formatting'

export default [
{ name: 'app/files-to-lint', files: ['**/*.{ts,mts,tsx,vue}'] },
{ name: 'app/files-to-ignore', ignores: ['**/dist/**', '**/coverage/**'] },
...vueTsEslintConfig(),
skipFormatting,
{
rules: {
'vue/multi-word-component-names': 'off', // 允许单词组件名(如 Home.vue)
'@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
},
},
]

VSCode 自动格式化

.vscode/settings.json:

1
2
3
4
5
6
7
8
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"[vue]": { "editor.defaultFormatter": "Vue.volar" }
}

配合 ESLint 和 Prettier 扩展,保存文件时就会自动修复风格问题。

七、组件与 API 自动导入

unplugin-auto-import 和 unplugin-vue-components 是 Vite 生态最香的工程化插件。配置后,ref、computed、Vue 内置组件、自己写的 components 都不需要手动 import,直接写就能用,IDE 也能正确提示。

安装

1
pnpm add -D unplugin-auto-import unplugin-vue-components

vite.config.ts 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

export default defineConfig({
plugins: [
vue(),
AutoImport({
imports: ['vue', 'vue-router', 'pinia'],
dts: 'src/auto-imports.d.ts', // 自动生成类型声明
resolvers: [ElementPlusResolver()],
}),
Components({
dirs: ['src/components'],
dts: 'src/components.d.ts',
resolvers: [ElementPlusResolver()],
}),
],
})

效果:

1
2
3
4
5
6
7
8
9
10
11
<script setup lang="ts">
// 不需要写 import { ref, computed } from 'vue'
const count = ref(0)
const double = computed(() => count.value * 2)

// 不需要写 import BaseButton from '@/components/BaseButton.vue'
</script>

<template>
<BaseButton @click="count++">{{ count }}</BaseButton>
</template>

注意:自动生成的 auto-imports.d.ts 和 components.d.ts 要加进 .gitignore 还是入库?建议入库,方便 CI 环境和团队成员直接使用,不依赖本地重新生成。

八、开发服务器代理

后端接口跨域是开发期最常见的问题。Vite 内置的代理可以一键解决,不必在 webpack 那样装中间件。

1
2
3
4
5
6
7
8
9
10
11
12
13
export default defineConfig({
server: {
port: 5173,
open: true,
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
},
})

前端请求 /api/user/list 实际会被代理到 http://localhost:3000/user/list,并自动剥掉 /api 前缀,避免跨域,也让 VITE_API_BASE_URL 在 dev/prod 之间切换时无感。

九、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
29
30
31
32
33
34
35
36
37
38
39
40
41
// src/api/request.ts
import axios from 'axios'
import type { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from 'axios'

const service: AxiosInstance = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL,
timeout: 10000,
})

service.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
const token = localStorage.getItem('token')
if (token) config.headers.Authorization = `Bearer ${token}`
return config
},
(error) => Promise.reject(error),
)

service.interceptors.response.use(
(response: AxiosResponse<ApiResponse>) => {
const { code, data, message } = response.data
if (code !== 0) return Promise.reject(new Error(message))
return data
},
(error) => {
if (error.response?.status === 401) {
// 跳转登录
}
return Promise.reject(error)
},
)

interface ApiResponse<T = unknown> {
code: number
data: T
message: string
}

export function request<T>(config: InternalAxiosRequestConfig): Promise<T> {
return service(config) as Promise<T>
}

调用层就清爽了:

1
2
3
4
5
6
// src/api/user.ts
import { request } from '@/api/request'
import type { UserInfo } from '@/types/user'

export const getUserInfo = (id: number) =>
request<UserInfo>({ url: `/user/${id}`, method: 'get' })

十、构建优化

包体积分析

1
pnpm add -D rollup-plugin-visualizer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { visualizer } from 'rollup-plugin-visualizer'

export default defineConfig({
build: {
rollupOptions: {
output: {
manualChunks: {
vue: ['vue', 'vue-router', 'pinia'],
echarts: ['echarts'],
},
},
},
},
plugins: [
vue(),
visualizer({ open: true, filename: 'stats.html' }),
],
})

常见优化项

  • 分包:把第三方大依赖单独打成一个 chunk,浏览器缓存命中率更高。
  • 按需引入:Element Plus 通过 unplugin-vue-components 的 Resolver 已经是按需;ECharts 用 echarts/core + use 按需注册。
  • gzip:部署端 nginx 开启 gzip_static on;,构建端用 vite-plugin-compression 生成 .gz 文件。
  • 图片资源:小于 4KB 的会被 Vite 内联成 base64,可以通过 build.assetsInlineLimit 调整阈值。

十一、最终启动流程

1
2
3
4
5
6
7
8
9
10
11
# 安装依赖
pnpm install

# 开发
pnpm dev

# 类型检查 + 构建
pnpm build-only # vue-tsc + vite build

# 预览构建产物
pnpm preview

一个完整的工程化骨架就跑起来了,目录清晰、规范统一、自动导入到位、构建产物可控。

小结

本文从零搭建了一套 Vite + Vue3 + TypeScript 工程化项目骨架,关键点回顾:

  1. 脚手架:用 create-vue 一次性集成 Vue3 + TS + Router + Pinia + ESLint + Prettier。
  2. 目录规范:按职责分层(api / composables / stores / types / views),后续维护成本低。
  3. 路径别名:vite.config.ts 与 tsconfig 双向配置 @,杜绝相对路径地狱。
  4. 环境变量:.env.development / .env.production 分离,并用 env.d.ts 增强 TS 类型。
  5. 代码规范:EditorConfig + ESLint Flat Config + Prettier,让保存即格式化。
  6. 自动导入:unplugin-auto-import + unplugin-vue-components,告别无意义的 import 重复劳动。
  7. 请求封装:axios 拦截器统一处理鉴权与错误。
  8. 构建优化:分包、可视化、按需引入,控制产物体积。

下一篇我们会在这套骨架之上深入 Vue3 Composition API,把 ref / reactive / computed / watch 的使用边界和最佳实践讲透。