vue3+ts+eslint+husky+prettier项目模板

1,973 阅读5分钟

一、创建项目

1. 控制台输入创建项目的命令:vue create vue3-template

Vue CLI v4.5.13
┌──────────────────────────────────────────┐
│                                          │
│   New version available 4.5.135.0.1   │
│     Run npm i -g @vue/cli to update!     │
│                                          │
└──────────────────────────────────────────┘

? Please pick a preset: 
  Default ([Vue 2] babel, eslint) 
  Default (Vue 3) ([Vue 3] babel, eslint) 
❯ Manually select features // 手动选择特性
? Check the features needed for your project: 
// 回车后
❯◉ Choose Vue version
 ◉ BabelTypeScriptProgressive Web App (PWA) SupportRouterVuexCSS Pre-processors // css预处理如less、sassLinter / Formatter // 代码规范相关Unit TestingE2E Testing
 // 回车后
? Choose a version of Vue.js that you want to start the project with 
  2.x 
❯ 3.x 
// 回车后
Use class-style component syntax? (y/N)  N // 是否选择class风格组件 
// 回车后
Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? Yes // 使用babel or tsc编译ts(babel可以添加polyfill)
// 回车后
Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Less // 选择css预处理器
// 回车后
Pick a linter / formatter config: Prettier // 选择eslint
// 回车后
Pick additional lint features: Lint on save // 保存时校验
// 回车后
Where do you prefer placing config for Babel, ESLint, etc.? In dedicated config files // 配置文件是否保存到单独的文件
// 回车后
Save this as a preset for future project? (y/N) n // N保存为模板

二、代码规范

1. 集成editorconfig配置

editorConfig有助于为不同的IDE编辑器上处理同一个项目在多个开发人员的开发过程中保持一致的编码风格。 在项目的根目录下创建 .editorconfig文件并配置编码风格(IDE编辑器会自动读取配置信息)。

# http://editorconfig.org

root = true

[*] #表示所有文件适用
charset = utf-8 #设置文件字符集为 utf-8
indent_style = space #缩进风格(tab | space)
indent_size = 2 #缩进大小
end_of_line = lf #控制换行类型(lf | cr | crlf)
trim_trailing_whitespace = true #去除行首的任意空白字符
insert_final_newline = true #始终在文件末尾插入一个新行

[*.md] #md 文件适用以下规则
max_line_length = off
trim_trailing_whitespace = false

📢: VS Code需要安装插件才可以自动读取配置:EditorConfig for VS Code

image.png

2.使用Prettier工具

Prettier是一款强大的代码格式化工具,支持JavaScript、typescript、css、less、jsx、angular、vue、GraphQL、JSON、markdown语言,是当下最流行的代码格式化工具

1). 安装Prettier: npm i prettier -D

2). 配置.prettierrc文件

{
  "useTabs": false,         // 使用tab缩进还是空格缩进
  "tabWidth": 2,            // tab是空格的情况下,是几个空格
  "printWidth": 80,         // 断行字符的长度
  "singleQuote": true,      // 使用单引号, 还是双引号
  "trailingComma": "none",  // 在多行输入的尾逗号是否添加
  "semi": false             // 语句末尾是否加分号
}

3). 配置.prettierignore忽略文件

/dist/*
.local
.output.js
/node_modules/**

**/*.svg
**/*.sh

/public/*

4). VS Code需要安装prettier插件

image.png

5). 测试prettier是否生效

  1. test1:在代码中保存代码

  2. test2:配置一次性修改的命令(在package.json中配置script:"prettier": "prettier --write ."

3. 使用ESLint检测

1). 在前面创建项目的时候,我们就选择了ESLint,所以Vue会默认帮助我们配置需要的ESLint环境。

2). VS Code需要安装ESLint插件

image.png

3). 解决eslint和prettier冲突的问题:

安装插件(vue在创建项目时,如果选择prettier,那么这两个插件会自动安装)

code: npm i eslint-plugin-prettier eslint-config-prettier -D

在.eslintrc.js文件中添加prettier插件:

  extends: [
    'plugin:vue/vue3-essential',
    'eslint:recommended',
    '@vue/typescript/recommended',
    '@vue/prettier',
    '@vue/prettier/@typescript-eslint',
    'plugin:prettier/recommended'
  ],

4.git Husky和eslint

虽然我们项目使用eslint了,但是不能保证组员提交代码之前都将eslint中的问题解决掉了,也就是我们希望仓库中的代码都是符合eslint规范的,那么我么需要在组员执行git commit命令的时候对其进行校验,如果不符合eslint规范,那么自动通过规范进行修复;如何做到这一点?可以通过Husky工具(husky是一个git hook功具,可以帮我们触发git提交的各个阶段:pre-commit、commit-msg、pre-push)那么如何使用husky呢?

1). 首先在工程下面执行命令:npx husky-init && npm install 命令做的几件事:

  • 安装husky相关的依赖
  • 在工程下创建.husky文件
  • 在package.json中添加脚本("prepare": "husky install") 2). 更改pre-commit文件内容

image.png

这个时候我们执行git commit的时候会自动对代码进行lint校验。

5. git commit规范

通常项目的git commit会按照统一的风格来提交,这样可以快速定位每次提交的内容,也方便之后对版本进行控制。但是如果每次手动来编写这些是比较麻烦的事情,所以我们可以在此使用一个工具:Commitizen(是一个帮助我们编写规范 commit message 的工具)

1). 安装Commitizen: npm i commitizen -D

2). 安装cz-conventional-changelog,并且初始化cz-conventional-changelog

npx commitizen init cz-conventional-changelog --save-dev --save-exact

这个命令会帮助我们安装cz-conventional-changelog且在package.json配置以下内容:

"config": {
  "commitizen": {
     "path": "./node_modules/cz-conventional-changelog"
   }
 }

此时候我们提交代码需要使用 npx cz

  • 第一步是选择type,本次更新的类型
Type作用
feat新增特性 (feature)
fix修复 Bug(bug fix)
docs修改文档 (documentation)
style代码格式修改(white-space, formatting, missing semi colons, etc)
refactor代码重构(refactor)
perf改善性能(A code change that improves performance)
test测试(when adding missing tests)
build变更项目构建或外部依赖(例如 scopes: webpack、gulp、npm 等)
ci更改持续集成软件的配置文件和 package 中的 scripts 命令,例如 scopes: Travis, Circle 等
chore变更构建流程或辅助工具(比如更改测试环境)
revert代码回退
  • 第二步选择本次修改的范围(作用域)
  • 第三步选择提交的信息(描述)
  • 第四步提交详细的描述信息
  • 第五步是否是一次重大的更改
  • 第六步是否影响某个open issue

📢 我们也可以在scripts中构建一个命令来执行 cz:"commit": "cz", 之后提交就可以使用命令 npm run commit提交代码

3). 代码提交验证

按照cz来规范了提交风格,但是依然有同事通过 git commit 按照不规范的格式提交应该怎么办呢?可以通过commitlint来限制提交;

3.1、安装 @commitlint/config-conventional 和 @commitlint/cli:

npm i @commitlint/config-conventional @commitlint/cli -D

3.2、在根目录创建commitlint.config.js文件,配置commitlint

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

3.3、使用husky生成commit-msg文件,验证提交信息:

npx husky add .husky/commit-msg "npx --no-install commitlint --edit $1"

三、第三方库集成

1. vue.config.js配置方式

方式一:直接通过CLI提供给我们的选项来配置:

  • 比如publicPath:配置应用程序部署的子目录(默认是 /,相当于部署在 https://www.my-app.com/);
  • 比如outputDir:修改输出的文件夹;

方式二:通过configureWebpack修改webpack的配置:

  • 可以是一个对象,直接会被合并;
  • 可以是一个函数,会接收一个config,可以通过config来修改配置;

方式三:通过chainWebpack修改webpack的配置:

  • 是一个函数,会接收一个基于webpack-chain的config对象,可以对配置进行修改;
const path = require('path')

module.exports = {
  outputDir: './build',
  // configureWebpack: {
  //   resolve: {
  //     alias: {
  //       views: '@/views'
  //     }
  //   }
  // }
  // configureWebpack: (config) => {
  //   config.resolve.alias = {
  //     '@': path.resolve(__dirname, 'src'),
  //     views: '@/views'
  //   }
  // },
  chainWebpack: (config) => {
    config.resolve.alias.set('@', path.resolve(__dirname, 'src')).set('views', '@/views')
  }
}

2. vue-router集成(初始化项目时选了vue-router可省略此步)

  1. 安装vue-router的最新版本:npm install vue-router@next

  2. 创建router对象

import { createRouter, createWebHashHistory } from 'vue-router'
import { RouteRecordRaw } from 'vue-router'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/main'
  },
  {
    path: '/main',
    component: () => import('../views/main/main.vue')
  },
  {
    path: '/login',
    component: () => import('../views/login/login.vue')
  }
]

const router = createRouter({
  routes,
  history: createWebHashHistory()
})

export default router
  1. 安装router
import router from './router'
createApp(App).use(router).mount('#app')
  1. 在App.vue中配置跳转
<div id="app">
  <router-link to="/login">登录</router-link>
  <router-link to="/main">首页</router-link>
  <router-view></router-view>
</div>

3. vuex集成(初始化项目时选了vuex可省略此步)

  1. 安装vuex:npm i vuex@next

  2. 创建store对象

import { createStore } from 'vuex'

const store = createStore({
  state() {
    return {
      message: 'hello vuex!'
    }
  }
})

export default store
  1. 安装store:createApp(App).use(router).use(store).mount('#app')

  2. app.vue中使用:<div>{{$store.state.message}}</div>

四、总结

项目的搭建就暂时到此为止了,下期会在此项目的基础之上集成element-plus。📢:此blog是学习coderwhy老师的vue3+ts的过程中做的个人学习笔记,老师真的太细了~