快速搭建 Vite+vue3+TS+ESLint+Prettier+Husky+Commitlint 项目

创建项目

进入项目目录,运行 yarn create vite 然后根据提示输入项目名,然后依次选择 Vue、TypeScript 即可创建一个简单的 Vue3+TS 项目。创建后按照提示进入项目文件夹并安装依赖,然后运行 yarn dev 即可启动项目

项目中可能会报Cannot find module 'vue'等错误

解决办法:禁用Vetur相关插件,启用Volar插件(如果使用的是vue2,则使用 Vetur 插件;使用 vue3 的话 ,要禁用 Vetur 插件,然后用 Volar 插件。两个插件不要同时使用,会冲突)

项目"main.ts" 文件中 "import App from './App.vue'" 部分有红色报错提示 "Cannot find module './App.vue' or its corresponding type declaration",其他文件有些import引入文件也报错。 报错原因:vite使用的是ts,ts不识别 .vue 后缀的文件

解决办法:在项目中找到env.d.tsvite-env.d.ts文件,加入下面声明

js 复制代码
declare module "*.vue" {
  import { DefineComponent } from "vue"
  const component: DefineComponent<{}, {}, any>
  export default component
}

代码规范

eslint

我们通过下面的命令可以非常简单地进行 ESLint 的初始化。

js 复制代码
npm init @eslint/config

按需选择完配置后,选择立即安装,就可一键安装相关依赖。安装成功后 ESLint 帮我们创建了 .eslintrc.cjs 配置文件(cjs 是指 CommonJS 格式)。

js 复制代码
module.exports = {
    "env": {
        "browser": true,
        "es2021": true
    },
    "extends": [
        "eslint:recommended",
        "plugin:@typescript-eslint/recommended",
        "plugin:vue/vue3-essential"
    ],
    "overrides": [
        {
            "env": {
                "node": true
            },
            "files": [
                ".eslintrc.{js,cjs}"
            ],
            "parserOptions": {
                "sourceType": "script"
            }
        }
    ],
    "parserOptions": {
        "ecmaVersion": "latest",
        "parser": "@typescript-eslint/parser",
        "sourceType": "module"
    },
    "plugins": [
        "@typescript-eslint",
        "vue"
    ],
    "rules": {
    }
}

package.jsonscript 中添加命令

js 复制代码
"scripts": {
    "lint": "eslint --ext .ts,.vue,.js, --fix --quiet ./"
  },

App.vue中添加一个未使用变量testProp

diff 复制代码
<script setup lang="ts">
   import HelloWorld from "./components/HelloWorld.vue";
+  const testProp = "sss";
</script>

运行yarn lint,报错,说明eslint配置生效

Prettier

一般 ESLint 用于检测代码风格代码规范,Prettier 用于对代码进行格式化。

安装依赖

js 复制代码
yarn add prettier -D

然后再根目录创建 .prettierrc.js 配置文件

js 复制代码
module.exports = {
  printWidth: 80,
  tabWidth: 2,
  useTabs: false,
  singleQuote: true,
  semi: false,
  trailingComma: "none",
  bracketSpacing: true
}

测试prettier是否生效,在 package.jsonscript 中添加命令

js 复制代码
"scripts": {
    "prettier":"prettier --write ./src/App.vue"
  },

修改App.vue代码

diff 复制代码
<script setup lang="ts">
- import HelloWorld from "./components/HelloWorld.vue";
+ import HelloWorld from "./components/HelloWorld.vue"
+
+
+
+
+
const testProp = "sss";
</script>

运行yarn prettier后,代码已经格式化,说明prettier配置有效,删除script 中的prettier测试命令

ESLint + Prettier

在eslint校验中加入Prettier格式化,安装依赖

js 复制代码
yarn add eslint-config-prettier eslint-plugin-prettier -D

更改 Eslint 的配置文件 .eslintrc.cjs, 在里面加入 Prettier 相关配置

diff 复制代码
module.exports = {
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended", 
    "plugin:vue/vue3-essential",
+    "plugin:prettier/recommended"
  ],
  "overrides": [
    {
      "env": {
        "node": true
      },
      "files": [".eslintrc.{js,cjs}"],
      "parserOptions": {
        "sourceType": "script"
      }
    }
  ],
  "parserOptions": {
    "ecmaVersion": "latest",
    "parser": "@typescript-eslint/parser",
    "sourceType": "module"
  },
  "plugins": [
    "@typescript-eslint", 
    "vue",
+    "prettier"
  ],
  "rules": {
+    "prettier/prettier": "error",
+   "arrow-body-style": "off",
+   "prefer-arrow-callback": "off"
  }
}

Husky + lint-staged

Husky

通过 Husky 在 Git commit 时进行代码校验。安装依赖

js 复制代码
yarn add husky -D

然后在 package.json 中添加脚本 prepare 并运行

js 复制代码
npm pkg set scripts.prepare="husky install"

npm run prepare

运行命令后会在项目根目录创建 .husky 文件夹。

现在给 Husky 添加一个 Hook

js 复制代码
npx husky add .husky/pre-commit "npm run lint"

添加 hook 之后,每次 git commit 之前都会先运行 npm run lint,通过之后才会提交代码。

lint-staged

每次提交都检测所有代码并不是一个好的决定,比如你只修改了文件 A 结果文件 B 报错了,但是文件 B 并不是你负责的模块,emmm改还是不改?

我们可以通过 lint-staged 只对暂存区的代码进行检验。

首先安装依赖

js 复制代码
yarn add lint-staged -D

然后在 package.json 添加相关配置。

js 复制代码
{
   "lint-staged": {
      "*.{ts,vue}": [
        "npm run lint",
        "prettier --write"
      ]
    }
}

并在 .husky/pre-commit 中替换 npm run lintnpx lint-staged。现在我们每次提交代码前都会对改动的文件进行 Lint 检查和prettier格式化。

commitlint

使用 commitlint 对提交信息进行校验。先安装依赖:

js 复制代码
yarn add @commitlint/cli @commitlint/config-conventional -D

然后在根目录创建配置文件 .commitlint.config.cjs,后缀.js可能会报CommonJS 语法错误(如下),将后缀改为.cjs即可

js 复制代码
module.exports = {
  extends: ["@commitlint/config-conventional"]
}

然后把 commitlint 命令也添加 Husky Hook。运行命令:

js 复制代码
npx husky add .husky/commit-msg "npx --no-install commitlint -e $HUSKY_GIT_PARAMS"

现在,运行命令git add . && git commit -m 'init',会发现经过eslint校验和prettier格式化后,提交信息不合法被拦截导致提交失败

而符合commitlint规范则可正常提交

每次都写这么大串东西,不仅繁琐还容易出错,折磨死人了,作为懒癌患者,必须拒绝!!!

commitizen

安装自动化提示工具

css 复制代码
npm i commitizen cz-conventional-changelog -D

然后在 package.json 中添加命令 commit

js 复制代码
{
  "scripts": {
    "commit": "git add . && git-cz"
  },
}

运行npm run commit,就可以快捷选择相应特性啦,按照提示一步一步下去就可以。到这一步基本就完成了,但是这个英文看着不舒服呀,而且太单调了,我想给他加点小图标。。。。。

安装cz适配器

js 复制代码
npm i  commitlint-config-cz  cz-customizable -D

在根目录创建 .cz-config.js,具体配置参考cz-customizable

js 复制代码
module.exports = {
  types: [
    {
      value: '✨ feat: ',
      name: '✨ feat:     新功能'
    },
    {
      value: '🐛 fix:',
      name: '🐛 fix:      修复bug'
    },
    {
      value: '📦️ build:',
      name: '📦️ build:    打包'
    },
    {
      value: '⚡️ perf:',
      name: '⚡️ perf:     性能优化'
    }, {
      value: '🎉 release:',
      name: '🎉 release:  发布正式版'
    }, {
      value: '💄 style:',
      name: '💄 style:    代码的样式美化'
    }, {
      value: '♻️  refactor:',
      name: '♻️  refactor: 重构'
    }, {
      value: '✏️  docs:',
      name: '✏️  docs:     文档变更'
    }, {
      value: '✅ test:',
      name: '✅ test:     测试'
    }, {
      value: '⏪️ revert:',
      name: '⏪️ revert:   回退'
    }, {
      value: '🚀 chore:',
      name: '🚀 chore:    构建/工程依赖/工具'
    }, {
      value: '👷 ci:',
      name: '👷 ci:       CI related changes'
    }
  ],
  messages: {
    type: '请选择提交类型(必填)',
    customScope: '请输入文件修改范围(可选)',
    subject: '请简要描述提交(必填)',
    body: '请输入详细描述(可选)',
    breaking: '列出任何BREAKING CHANGES(可选)',
    footer: '请输入要关闭的issue(可选)',
    confirmCommit: '确定提交此说明吗?'
  },
  allowCustomScopes: true, 
  // 跳过问题
  skipQuestions: ['body', 'footer'],
  subjectLimit: 72
}

更新package.jsoncommit命令,使用自定义命令

diff 复制代码
{
  "scripts": {
-    "commit": "git add . && git-cz"
+    "commit": "git add . && cz-customizable" //有些window电脑不认cz-customizable,建议使用用下面commit
+    "commit": "git add . &&  git cz"
  },
}

更新 commitlint.config.cjs

diff 复制代码
module.exports = {
-  extends: ["@commitlint/config-conventional"],
+  extends: ["cz"],
};

运行npm run commit,报错,还是commonjs的问题

.cz-config.js后缀改为cjs.cz-config.cjs,在package.json中添加配置文件路径

diff 复制代码
{
  "config": {
    "commitizen": {
      "path": "./node_modules/cz-customizable"
    },
+    "cz-customizable": {
+     "config": ".cz-config.cjs"
+    }
  }
}

运行npm run commit,按照步骤一步一步填写就好啦

eslint-plugin-simple-import-sort

自动修复 import 排序,墙裂推荐 墙裂推荐 墙裂推荐的插件

安装插件

js 复制代码
yarn add eslint-plugin-simple-import-sort -D

.eslintrc.cjs中配置

diff 复制代码
module.exports = {
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": [
    "eslint:recommended", 
    "plugin:@typescript-eslint/recommended", 
    "plugin:vue/vue3-essential", 
    "plugin:prettier/recommended"
  ],
  "overrides": [
    {
      "env": {
        "node": true
      },
      "files": [".eslintrc.{js,cjs}"],
      "parserOptions": {
        "sourceType": "script"
      }
    }
  ],
  "parserOptions": {
    "ecmaVersion": "latest",
    "parser": "@typescript-eslint/parser",
    "sourceType": "module"
  },
  "plugins": [
    "@typescript-eslint", 
    "vue", 
    "prettier",
+   "simple-import-sort"
],
  "rules": {
    "prettier/prettier": "error",
    "arrow-body-style": "off",
    "prefer-arrow-callback": "off",
+    "simple-import-sort/imports": [
+        "error", 
+        {
+          groups: [
+            [
+              '^vue', // vue放在首行
+              // 以字母(或数字或下划线)或"@"后面跟着字母开头的东西,通常为nodeModules引入
+              '^@?\\w', 
+              '^@(/.*|$)', // 内部导入 "@/"
+              '^\\.\\.(?!/?$)', // 父级导入. 把 `..` 放在最后.
+              '^\\.\\./?$',
+              // 同级导入. 把同一个文件夹.放在最后
+              '^\\./(?=.*/)(?!/?$)',
+              '^\\.(?!/?$)',
+              '^\\./?$',
+              '^.+\\.?(css|less|scss)$', // 样式导入.
+              '^\\u0000', // 带有副作用导入,比如import 'a.css'这种.
+            ],
+          ]
+        }
+      ]
  }
}

提交后自动修复import的排列顺序,比之前看着舒服多了,我的强迫症终于好了😏😏😏

相关推荐
一 乐31 分钟前
租拼车平台|小区租拼车管理|基于java的小区租拼车管理信息系统小程序设计与实现(源码+数据库+文档)
java·数据库·vue.js·微信·notepad++·拼车
寻找09之夏4 小时前
【Vue3实战】:用导航守卫拦截未保存的编辑,提升用户体验
前端·vue.js
多多米10055 小时前
初学Vue(2)
前端·javascript·vue.js
看到请催我学习5 小时前
内存缓存和硬盘缓存
开发语言·前端·javascript·vue.js·缓存·ecmascript
golitter.7 小时前
Vue组件库Element-ui
前端·vue.js·ui
道爷我悟了7 小时前
Vue入门-指令学习-v-on
javascript·vue.js·学习
长路 ㅤ   8 小时前
vite学习教程02、vite+vue2配置环境变量
前端·vite·环境变量·跨环境配置
.生产的驴8 小时前
Electron Vue框架环境搭建 Vue3环境搭建
java·前端·vue.js·spring boot·后端·electron·ecmascript
老齐谈电商8 小时前
Electron桌面应用打包现有的vue项目
javascript·vue.js·electron
LIURUOYU4213089 小时前
vue.js组建开发
vue.js