项目开发规范

97 阅读3分钟

1. 创建一个vue项目

按照vue官方文档 运行命令行

npm create vue@latest

全部选否一路走下去,创建项目

image.png

2. eslint 配置

按照 eslint官方文档

按照自己的需求,选择相应的配置

image.png

添加流行的eslint规则配置

  • eslint-config-airbnb-base:airbnb风格的规则
  • eslint-plugin-import:支持检测es6+的import/export语法,防止文件路径引入错误或拼写错误。

将airbnb相关配置添加到 .eslintrc.cjs

image.png

package.json 文件 script 下添加指令

image.png

"lint": "eslint . --ext .vue,.js,.cjs --fix --ignore-path .gitignore"

运行指令格式化所有相应文件, 至此我们的eslint配置完成

npm run lint

prettier 配置

相对于eslint 来说,eslint主要注重代码的语法错误的检查,prettier而是更注重代码的格式检查

prettier官方文档

npm i prettier -D

根目录下新建一个文件夹 .prettierrc.cjs

常用配置如下

module.exports = {
  printWidth: 100, //每行最多显示的字符数
  tabWidth: 2, //tab的宽度 2个字符
  useTabs: false, //禁止使用tab代替空格
  semi: true, //结尾使用分号
  singleQuote: true, //使用单引号代替双引号
  trailingComma: 'none', //结尾是否添加逗号
  bracketSpacing: true, //对象括号俩边是否用空格隔开
  bracketSameLine: true, //组件最后的尖括号不另起一行
  arrowParens: 'always', //箭头函数参数始终添加括号
  htmlWhitespaceSensitivity: 'ignore', //html存在空格是不敏感的
  vueIndentScriptAndStyle: false, //vue 的script和style的内容是否缩进
  endOfLine: 'auto', //行结尾形式 mac和linux是\n  windows是\r\n
  singleAttributePerLine: false //组件或者标签的属性是否控制一行只显示一个属性
};

prettier 与 eslint 的兼容性

由于格式化的时候,程序不知道我们采用什么格式化,到底是 prettier 还是 eslint

所以 我们会发现 eslint 和 prettier 一起配置的时候,会发现经常 eslint 不生效或者 prettier

这时候 我们需要 添加一个插件,帮助我们采用 eslint 去 调用 prettier 的配置,从而实现 代码语法&代码格式的双重检验修复

这个插件就是 @vue/eslint-config-prettier

运行 npm i @vue/eslint-config-prettier -D

在文件 .eslintrc.cjs 添加配置

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

不清楚为啥 eslint-config-prettier在这里失效, 暂时就只知道要使用@vue/eslint-config-prettier

再次运行命令 npm run lint 格式化我们所有的代码

commitlint配置

commitlint 是为了规范我们团队成员在提交代码的时候,随意填写一些没用的message信息

这种无用的message信息,很多时候在对代码回溯,查看的时候对我们的非本模块的开发同学造成误导。

详细链接

Getting start

# For Windows:
npm install --save-dev @commitlint/config-conventional @commitlint/cli

# Configure commitlint to use conventional config
echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js
# Install Husky v6
npm install husky --save-dev
# or
yarn add husky --dev
# Activate hooks
npx husky install
# or
yarn husky install

Add Hook

npx husky add .husky/commit-msg  'npx --no -- commitlint --edit ${1}'

这是后我们提交git的规范需要

Q: 当我们运行 npx husky 的时候会报错!

这是因为 我们应该先初始化 git配置文件 运行 git init 即可

Q: 当我们提交代码的时候怎么都提交不成功,并会返回一个乱码的标识

这是 应为文档让我们运行的命令 echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js 创建的文件格式不正确,用vscode修改为 utf-8 即可

配置lint-staged

安装

npm i lint-staged -D

修改 package.json

添加脚本

添加 lint-stage配置

"lint-staged": {
    "src/**/*.{js,vue}": "npm run lint"
}

注册 hook

npx husky add .husky/pre-commit "npx lint-staged"

image.png

提示 运行以下命令会在package.json中自动添加 'prepare' 脚本 这个脚本 会在install之后 立马执行 npm pkg set scripts.prepare="husky install"