HiHuo
首页
博客
手册
工具
首页
博客
手册
工具
  • Vue & CSS 进阶

    • 第0章:工具链与开发体验
    • 第1章:TypeScript 核心
    • 第2章:CSS 现代能力
    • 第3章:Vue3 核心与原理
    • 第4章:路由与状态管理
    • 第5章:工程化与性能
    • 第6章:测试与质量
    • 第7章:CSS 进阶专题
    • 第8章:项目实战A - SaaS仪表盘
    • 第9章:项目实战B - 内容社区
    • 第10章:Vue 内核深入
    • 第11章:微前端与部署
    • CSS 变量体系与主题系统深度指南
    • 前端安全与防护专题
    • CSS 专题:动效优化与微交互
    • CSS 专题:图片与图形处理
    • 实时通信与WebSocket专题
    • 开发工具与调试技巧专题
    • 新兴技术与未来趋势专题
    • 移动端开发与PWA专题
    • 附录A:代码片段库
    • 附录B:练习题集

第0章:工具链与开发体验

工欲善其事,必先利其器。本章将搭建完整的现代前端开发环境,建立规范的代码工作流。

📋 本章内容

  • 环境搭建
  • 代码规范配置
  • Git 工作流
  • 开发工具配置
  • 实战练习

🛠 环境搭建

必备环境

1. Node.js 环境

# 检查 Node.js 版本(需要 >= 18)
node --version

# 如果版本过低,建议使用 nvm 管理 Node.js 版本
# 安装 nvm (macOS/Linux)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash

# 安装并使用 Node.js 18
nvm install 18
nvm use 18

2. 包管理器:pnpm

pnpm 相比 npm 和 yarn 有以下优势:

  • 磁盘空间节省:通过硬链接共享依赖
  • 安装速度快:并行安装,缓存机制
  • 严格依赖管理:避免幽灵依赖问题
# 安装 pnpm
npm install -g pnpm

# 验证安装
pnpm --version

# 配置 pnpm(可选)
pnpm config set registry https://registry.npmmirror.com/

3. 创建项目

# 使用 Vite 创建 Vue3 + TypeScript 项目
pnpm dlx vite@latest my-vue-app -- --template vue-ts

# 进入项目目录
cd my-vue-app

# 安装依赖
pnpm install

# 启动开发服务器
pnpm dev

项目结构解析

my-vue-app/
├── public/                 # 静态资源
├── src/
│   ├── assets/            # 资源文件
│   ├── components/        # 组件
│   ├── App.vue           # 根组件
│   ├── main.ts           # 入口文件
│   └── vite-env.d.ts     # Vite 类型声明
├── index.html            # HTML 模板
├── package.json          # 项目配置
├── tsconfig.json         # TypeScript 配置
├── tsconfig.node.json    # Node.js TypeScript 配置
└── vite.config.ts        # Vite 配置

📝 代码规范配置

ESLint 配置

ESLint 是 JavaScript/TypeScript 代码质量检查工具,能帮助发现潜在问题并统一代码风格。

1. 安装 ESLint 相关依赖

pnpm add -D eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-vue prettier eslint-config-prettier

2. 创建 ESLint 配置文件

创建 .eslintrc.cjs:

module.exports = {
  root: true,
  env: {
    browser: true,
    es2021: true,
    node: true
  },
  extends: [
    'eslint:recommended',
    '@typescript-eslint/recommended',
    'plugin:vue/vue3-recommended',
    'prettier'
  ],
  parser: 'vue-eslint-parser',
  parserOptions: {
    ecmaVersion: 'latest',
    parser: '@typescript-eslint/parser',
    sourceType: 'module'
  },
  plugins: ['vue', '@typescript-eslint'],
  rules: {
    // Vue 相关规则
    'vue/multi-word-component-names': 'off',
    'vue/no-v-html': 'warn',
    
    // TypeScript 相关规则
    '@typescript-eslint/no-unused-vars': 'error',
    '@typescript-eslint/no-explicit-any': 'warn',
    '@typescript-eslint/explicit-function-return-type': 'off',
    
    // 通用规则
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'
  }
}

3. 创建 ESLint 忽略文件

创建 .eslintignore:

node_modules
dist
*.min.js
public

Prettier 配置

Prettier 是代码格式化工具,与 ESLint 配合使用。

1. 创建 Prettier 配置文件

创建 .prettierrc:

{
  "semi": false,
  "singleQuote": true,
  "tabWidth": 2,
  "trailingComma": "none",
  "printWidth": 80,
  "endOfLine": "lf",
  "arrowParens": "avoid"
}

2. 创建 Prettier 忽略文件

创建 .prettierignore:

node_modules
dist
*.min.js
public
package-lock.json
pnpm-lock.yaml

配置 package.json 脚本

{
  "scripts": {
    "dev": "vite",
    "build": "vue-tsc && vite build",
    "preview": "vite preview",
    "lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore",
    "format": "prettier --write src/",
    "type-check": "vue-tsc --noEmit"
  }
}

🔧 Git 工作流

提交规范

使用 commitlint 和 husky 确保提交信息规范。

1. 安装依赖

pnpm add -D @commitlint/cli @commitlint/config-conventional husky lint-staged

2. 配置 commitlint

创建 commitlint.config.js:

module.exports = {
  extends: ['@commitlint/config-conventional'],
  rules: {
    'type-enum': [
      2,
      'always',
      [
        'feat',     // 新功能
        'fix',      // 修复
        'docs',     // 文档
        'style',    // 格式
        'refactor', // 重构
        'perf',     // 性能
        'test',     // 测试
        'chore',    // 构建/工具
        'ci',       // CI
        'build',    // 构建
        'revert'    // 回滚
      ]
    ]
  }
}

3. 配置 husky

# 初始化 husky
npx husky install

# 添加 pre-commit 钩子
npx husky add .husky/pre-commit "npx lint-staged"

# 添加 commit-msg 钩子
npx husky add .husky/commit-msg "npx --no -- commitlint --edit \$1"

4. 配置 lint-staged

在 package.json 中添加:

{
  "lint-staged": {
    "*.{js,jsx,ts,tsx,vue}": [
      "eslint --fix",
      "prettier --write"
    ],
    "*.{json,md}": [
      "prettier --write"
    ]
  }
}

提交信息规范

<type>(<scope>): <subject>

<body>

<footer>

示例:

feat(auth): add user login functionality

- Add login form component
- Implement JWT token handling
- Add route guards for protected pages

Closes #123

🎨 开发工具配置

VS Code 配置

1. 推荐插件

{
  "recommendations": [
    "Vue.volar",                    // Vue 语言支持
    "Vue.vscode-typescript-vue-plugin", // TypeScript Vue 插件
    "esbenp.prettier-vscode",       // Prettier
    "dbaeumer.vscode-eslint",       // ESLint
    "bradlc.vscode-tailwindcss",    // Tailwind CSS(可选)
    "ms-vscode.vscode-typescript-next", // TypeScript
    "formulahendry.auto-rename-tag", // 自动重命名标签
    "christian-kohler.path-intellisense", // 路径智能提示
    "ms-vscode.vscode-json"         // JSON 支持
  ]
}

2. VS Code 设置

创建 .vscode/settings.json:

{
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "typescript.preferences.importModuleSpecifier": "relative",
  "vue.codeActions.enabled": true,
  "vue.complete.casing.tags": "kebab",
  "vue.complete.casing.props": "camel"
}

3. 工作区配置

创建 .vscode/extensions.json:

{
  "recommendations": [
    "Vue.volar",
    "Vue.vscode-typescript-vue-plugin",
    "esbenp.prettier-vscode",
    "dbaeumer.vscode-eslint"
  ]
}

🧪 实战练习

练习1:环境验证

  1. 创建新的 Vue3 + TypeScript 项目
  2. 配置 ESLint 和 Prettier
  3. 验证代码格式化是否正常工作
# 创建项目
pnpm dlx vite@latest practice-app -- --template vue-ts
cd practice-app

# 安装代码规范工具
pnpm add -D eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-vue prettier eslint-config-prettier

# 配置 ESLint 和 Prettier(参考上面的配置)
# 测试格式化
pnpm format

练习2:Git 工作流

  1. 初始化 Git 仓库
  2. 配置 commitlint 和 husky
  3. 提交代码并验证提交信息规范
# 初始化 Git
git init
git add .
git commit -m "feat: initial project setup"

# 配置提交规范工具
pnpm add -D @commitlint/cli @commitlint/config-conventional husky lint-staged

# 配置 husky(参考上面的配置)
# 测试提交
git add .
git commit -m "feat: add code quality tools"

练习3:组件开发

创建一个简单的计数器组件,验证开发环境:

<!-- src/components/Counter.vue -->
<template>
  <div class="counter">
    <h2>计数器</h2>
    <p>当前值: {{ count }}</p>
    <button @click="increment">+1</button>
    <button @click="decrement">-1</button>
    <button @click="reset">重置</button>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

const count = ref(0)

const increment = () => {
  count.value++
}

const decrement = () => {
  count.value--
}

const reset = () => {
  count.value = 0
}
</script>

<style scoped>
.counter {
  text-align: center;
  padding: 20px;
}

button {
  margin: 0 5px;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  background-color: #42b883;
  color: white;
  cursor: pointer;
}

button:hover {
  background-color: #369870;
}
</style>

📚 最佳实践

1. 项目结构规范

src/
├── components/          # 通用组件
│   ├── base/           # 基础组件
│   └── business/       # 业务组件
├── views/              # 页面组件
├── composables/        # 组合式函数
├── stores/             # 状态管理
├── utils/              # 工具函数
├── types/              # 类型定义
├── assets/             # 静态资源
└── styles/             # 样式文件

2. 命名规范

  • 组件名:PascalCase(如 UserProfile.vue)
  • 文件名:kebab-case(如 user-profile.vue)
  • 变量名:camelCase(如 userName)
  • 常量名:UPPER_SNAKE_CASE(如 API_BASE_URL)

3. 导入规范

// 1. 第三方库
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'

// 2. 内部模块(绝对路径)
import { useAuth } from '@/composables/useAuth'
import UserCard from '@/components/UserCard.vue'

// 3. 相对路径
import './styles.css'

🚨 常见问题

1. ESLint 报错但代码能运行

问题:TypeScript 类型检查通过,但 ESLint 报错 解决:检查 .eslintrc.cjs 中的 parser 配置

parser: 'vue-eslint-parser',
parserOptions: {
  parser: '@typescript-eslint/parser'
}

2. Prettier 与 ESLint 冲突

问题:格式化后 ESLint 报错 解决:确保安装了 eslint-config-prettier 并在 extends 中最后引入

3. Git hooks 不生效

问题:提交时没有触发 pre-commit 检查 解决:确保 husky 已正确安装并初始化

npx husky install

📖 延伸阅读

  • ESLint 官方文档
  • Prettier 官方文档
  • Husky 官方文档
  • Commitlint 官方文档
  • Vue 3 官方文档

下一章预告:我们将深入学习 TypeScript 的核心概念,掌握类型系统、泛型、条件类型等高级特性,为 Vue 开发打下坚实的类型基础。

Next
第1章:TypeScript 核心