摘要:
本文手把手教你从零搭建一个企业级 Vue 3 开发环境,涵盖 Vite 初始化、TypeScript 配置、ESLint + Prettier 代码规范、Husky Git 提交校验、路径别名设置等全流程。所有配置均基于2026 年最新生态(Vite 6 + Vue 3.5 + TS 5.6),提供完整可运行代码,助你告别“配置地狱”,专注业务开发。
关键词:Vue 3;Vite;TypeScript;ESLint;Prettier;Husky;CSDN
一、为什么需要标准化环境?
很多初学者直接npm create vue@latest后就开始写代码,结果后期遇到:
- 团队代码风格混乱
- Git 提交包含格式错误
- 路径引用写成
../../../components - 类型检查缺失导致线上 bug
标准化环境 = 开发效率 × 代码质量 × 团队协作
本文将带你搭建一个开箱即用、可复用、可维护的 Vue 3 项目骨架。
二、初始化项目(Vite + Vue 3 + TS)
2.1 前置要求
- Node.js ≥ 18.0(推荐 20.x)
- npm ≥ 9.0 或 pnpm ≥ 8.0(本文用 pnpm)
# 检查版本 node -v # v20.15.0 pnpm -v # 8.15.02.2 创建项目
pnpm create vue@latest my-vue-app交互式选择:
✔ Project name: … my-vue-app ✔ Add TypeScript? … Yes ✔ Add JSX Support? … No ✔ Add Vue Router for Single Page Application development? … Yes ✔ Add Pinia for state management? … Yes ✔ Add Vitest for Unit Testing? … Yes ✔ Add an End-to-End Testing Solution? … No ✔ Add ESLint for code quality? … Yes ✔ Add Prettier for code formatting? … Yes✅关键点:务必勾选TypeScript、ESLint、Prettier、Pinia、Router
进入目录并安装依赖:
cd my-vue-app pnpm install三、核心配置详解(附完整代码)
3.1 配置 TypeScript(tsconfig.json)
默认配置较宽松,我们增强类型安全:
// tsconfig.json { "compilerOptions": { "target": "ES2020", "useDefineForClassFields": true, "module": "ESNext", "lib": ["ES2020", "DOM", "DOM.Iterable"], "skipLibCheck": true, /* Bundler mode */ "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "preserve", /* Linting */ "strict": true, // 启用所有严格类型检查 "noUnusedLocals": true, // 未使用变量报错 "noUnusedParameters": true, // 未使用参数报错 "noFallthroughCasesInSwitch": true, "noImplicitReturns": true, "noUncheckedIndexedAccess": true, // 索引访问需判空 /* Path Alias */ "baseUrl": ".", "paths": { "@/*": ["src/*"] } }, "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"], "references": [{ "path": "./tsconfig.node.json" }] }💡作用:
strict: true强制类型安全paths支持@/components代替相对路径
3.2 配置 Vite(vite.config.ts)
增强开发体验与构建能力:
// vite.config.ts import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import path from 'node:path' // https://vitejs.dev/config/ export default defineConfig({ plugins: [vue()], resolve: { alias: { '@': path.resolve(__dirname, './src') } }, server: { port: 3000, // 固定端口 open: true, // 启动自动打开浏览器 proxy: { '/api': { target: 'http://localhost:8080', changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, '') } } }, build: { outDir: 'dist', sourcemap: true, // 生成 source map rollupOptions: { output: { manualChunks: { // 代码分割 vendor: ['vue', 'vue-router', 'pinia'], element: ['element-plus'] } } } } })🔧关键配置说明:
alias:配合 TS paths 实现路径别名proxy:解决开发跨域manualChunks:优化打包体积
3.3 ESLint + Prettier 统一代码风格
步骤 1:安装依赖
pnpm add -D eslint-config-prettier eslint-plugin-vue @typescript-eslint/eslint-plugin @typescript-eslint/parser步骤 2:配置 .eslintrc.cjs
// .eslintrc.cjs module.exports = { env: { browser: true, es2021: true, node: true }, extends: [ 'eslint:recommended', 'plugin:@typescript-eslint/recommended', 'plugin:vue/vue3-essential', 'prettier' // 必须放最后,覆盖其他规则 ], parser: 'vue-eslint-parser', parserOptions: { ecmaVersion: 'latest', parser: '@typescript-eslint/parser', sourceType: 'module', ecmaFeatures: { jsx: true } }, plugins: ['vue', '@typescript-eslint'], rules: { // 自定义规则 'vue/multi-word-component-names': 'off', // 允许单文件组件名 '@typescript-eslint/no-explicit-any': 'warn', 'vue/no-setup-props-destructure': 'off' } }步骤 3:配置 .prettierrc
// .prettierrc { "semi": false, "singleQuote": true, "printWidth": 80, "tabWidth": 2, "trailingComma": "es5", "bracketSpacing": true, "arrowParens": "avoid" }步骤 4:添加脚本(package.json)
{ "scripts": { "lint": "eslint . --ext .vue,.js,.jsx,.ts,.tsx --fix --ignore-path .gitignore", "format": "prettier --write src/" } }✅效果:
- 保存时自动格式化(需 VS Code 安装 Prettier 插件)
- 提交前自动 lint
3.4 集成 Husky + lint-staged(Git 提交校验)
防止格式错误代码进入仓库。
安装
pnpm add -D husky lint-staged初始化 Husky
pnpm exec husky install在 package.json 添加 prepare 脚本
{ "scripts": { "prepare": "husky install" } }创建提交前钩子
pnpm exec husky add .husky/pre-commit "pnpm lint-staged"配置 lint-staged(package.json)
{ "lint-staged": { "*.{vue,js,ts,jsx,tsx}": ["eslint --fix", "prettier --write"] } }🛡️效果:
每次git commit时,自动修复格式问题,失败则阻止提交。
四、项目结构优化(src 目录)
采用企业级分层结构:
src/ ├── assets/ # 静态资源 ├── components/ # 通用组件 ├── composables/ # 自定义组合函数 ├── layouts/ # 布局组件 ├── pages/ # 页面级组件 ├── router/ # 路由配置 ├── stores/ # Pinia store ├── types/ # 全局类型定义 ├── utils/ # 工具函数 ├── views/ # 视图(可与 pages 合并) ├── App.vue └── main.ts💡建议:
- 组件按功能命名(如
UserAvatar.vue)- 避免深层嵌套(最多 2 层)
五、编写第一个组件(验证环境)
5.1 创建 HelloWorld 组件
<!-- src/components/HelloWorld.vue --> <template> <div class="hello"> <h1>{{ msg }}</h1> <p>当前计数:{{ count }}</p> <button @click="increment">+1</button> </div> </template> <script setup lang="ts"> import { ref, computed } from 'vue' // Props 定义 interface Props { msg: string } const props = defineProps<Props>() // 响应式状态 const count = ref(0) // 计算属性 const doubleCount = computed(() => count.value * 2) // 方法 const increment = () => { count.value++ } // 暴露给模板(非必须,仅演示) defineExpose({ increment }) </script> <style scoped> .hello { text-align: center; margin: 20px; } </style>5.2 在 App.vue 中使用
<!-- src/App.vue --> <template> <div id="app"> <HelloWorld msg="欢迎来到 Vue 3 + TS 世界!" /> </div> </template> <script setup lang="ts"> import HelloWorld from '@/components/HelloWorld.vue' </script>✅验证:
运行pnpm dev,浏览器打开http://localhost:3000,看到按钮可点击,证明环境配置成功!
六、常见问题与避坑指南
❌ 问题 1:路径别名@不生效
原因:Vite 和 TS 配置未同步
解决:
- 确保
vite.config.ts有alias: { '@': ... } - 确保
tsconfig.json有paths: { "@/*": ["src/*"] }
❌ 问题 2:ESLint 报错 “Parsing error: The keyword ‘const’ is reserved”
原因:parser 未正确设置
解决:在.eslintrc.cjs中指定:
parser: 'vue-eslint-parser', parserOptions: { parser: '@typescript-eslint/parser' }❌ 问题 3:Husky 钩子不触发
原因:未执行husky install
解决:
pnpm run prepare # 或 pnpm exec husky install七、总结:你的标准化 Vue 3 项目已就绪!
通过本文,你已成功搭建一个包含以下特性的项目:
✅现代化构建:Vite 6 + Vue 3.5
✅强类型支持:TypeScript 5.6 + 严格模式
✅代码规范:ESLint + Prettier + Husky
✅开发体验:路径别名、代理、热更新
✅可扩展架构:清晰的目录结构
下一步建议:
- 将此项目模板保存为 GitHub Template
- 开始学习 [第 2 篇:响应式系统源码剖析]
- 尝试添加 Element Plus 并配置主题
附录:完整依赖列表(package.json)
{ "name": "my-vue-app", "version": "0.1.0", "private": true, "type": "module", "scripts": { "dev": "vite", "build": "vue-tsc && vite build", "preview": "vite preview", "test:unit": "vitest", "lint": "eslint . --ext .vue,.js,.ts --fix", "format": "prettier --write src/", "prepare": "husky install" }, "dependencies": { "vue": "^3.5.0", "vue-router": "^4.4.0", "pinia": "^2.2.0" }, "devDependencies": { "@vitejs/plugin-vue": "^5.0.0", "@typescript-eslint/eslint-plugin": "^7.0.0", "@typescript-eslint/parser": "^7.0.0", "eslint": "^8.56.0", "eslint-config-prettier": "^9.1.0", "eslint-plugin-vue": "^9.20.0", "husky": "^9.0.0", "lint-staged": "^15.0.0", "prettier": "^3.2.0", "typescript": "~5.6.0", "vite": "^6.0.0", "vue-tsc": "^2.0.0" }, "lint-staged": { "*.{vue,js,ts}": ["eslint --fix", "prettier --write"] } }