返回

Vue3 + TypeScript + Vite 项目开发指南:从零构建规范项目

前端

搭建规范的 Vue3 + TypeScript + Vite 项目

项目搭建

使用 Vue CLI 创建项目

npx vue create <project-name>

选择选项

  • 项目类型:Default (Vue 3)
  • 语言选项:TypeScript

代码规范

安装 ESLint + Prettier

npm install --save-dev eslint
npm install --save-dev prettier

创建配置文件

  • .eslintrc.js:ESLint 配置
  • .prettierrc.js:Prettier 配置

提交规范

安装 Commitlint + Husky

npm install --save-dev commitlint
npm install --save-dev husky

创建配置文件

  • .commitlintrc.js:Commitlint 配置
  • .husky/pre-commit:Husky 钩子

单元测试

安装 Jest + Vue Test Utils

npm install --save-dev jest
npm install --save-dev @vue/test-utils

创建测试文件

  • tests/App.spec.js:App 组件的测试文件

自动化部署

安装 GitHub Actions + Netlify

npx gh-actions init

创建 GitHub Actions 工作流文件

  • .github/workflows/deploy.yml:部署工作流文件

代码示例

ESLint 配置

module.exports = {
  root: true,
  parser: '@typescript-eslint/parser',
  plugins: [
    '@typescript-eslint'
  ],
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended'
  ]
};

Prettier 配置

module.exports = {
  printWidth: 100,
  tabWidth: 2,
  useTabs: false,
  semi: true,
  singleQuote: true,
  trailingComma: 'all',
  bracketSpacing: true,
  jsxBracketSameLine: false,
  arrowParens: 'avoid',
  endOfLine: 'auto'
};

Commitlint 配置

module.exports = {
  extends: ['@commitlint/config-conventional']
};

Husky 钩子

#!/bin/sh
npx commitlint --edit $1

App 组件测试

import { shallowMount } from '@vue/test-utils';
import App from '../src/App.vue';

describe('App', () => {
  it('renders a message', () => {
    const wrapper = shallowMount(App);
    expect(wrapper.text()).toBe('Hello Vue!');
  });
});

GitHub Actions 工作流文件

name: Deploy

on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: Netlify/actions/netlify-deploy@v2.4.4
        with:
          site_id: YOUR_NETLIFY_SITE_ID
          auth_token: YOUR_NETLIFY_AUTH_TOKEN

常见问题解答

1. 如何确保代码符合规范?

  • 使用 ESLint + Prettier 进行代码检查。
  • 在提交代码前,运行 npm run lint

2. 如何在提交代码时自动检查提交规范?

  • 使用 Commitlint + Husky。
  • 创建提交规范钩子 npx commitlint --edit $1

3. 如何编写有效的单元测试?

  • 使用 Jest + Vue Test Utils。
  • 遵循测试金字塔原则:写一个单元测试覆盖一个组件。

4. 如何自动部署代码?

  • 使用 GitHub Actions + Netlify。
  • 创建 GitHub Actions 工作流文件来触发部署。

5. 如何定制代码规范和提交规范?

  • 修改 .eslintrc.js.commitlintrc.js 文件。
  • 根据项目需要调整规则。

结论

通过遵循这些步骤,您可以搭建一个符合代码规范、提交规范、单元测试和自动化部署要求的规范的 Vue3 + TypeScript + Vite 项目。这将提高代码质量,简化提交过程,并确保项目始终处于最新状态。