Skip to content

起步

​ 一个前端项目往往都需要多人开发,为了便于维护与管理,往往都需要对代码质量、代码 格式(CSS、JS、HTML)以及 git 提交注释都要进行统一规范化。

​ 一般前端规范化通常包含了:

  1. ESLint:ESLint 是一个用于识别和报告 JavaScript 代码中的模式问题的工具,可以帮 助团队遵循统一的编码规范,发现潜在的代码错误和漏洞。

  2. Prettier:Prettier 是一个代码格式化工具,可以自动格式化代码,使代码风格保持一 致,避免团队成员在代码格式上的争议。

  3. Husky:Husky 是一个 Git 钩子工具,可以在代码提交、代码推送等操作前后执行预定 义的脚本,比如在提交代码前运行 ESLint 和 Prettier。

  4. lint-staged:lint-staged 是一个在提交阶段运行 linters 的工具,可以只对提交的 文件进行检查,提高 lint 的效率。

  5. Commitlint:Commitlint 是一个用于检查提交信息是否符合规范的工具,可以帮助团队 统一提交信息的格式。

  6. Commitizen:Commitizen 是一个用于规范化提交信息的工具,可以通过交互式命令行帮 助开发者生成符合规范的提交信息,提高提交信息的质量和统一性。

  7. stylelint:用来检查 css 的,提升 css 的可读性。

    通常每个项目可能的规范都不一样,所以一般都是一个项目里面集成了一套规范化方案 。

扩展:

  1. 文档规范化:可以使用工具如 Docsify、Docusaurus、GitBook 等来管理项目文档,这 些工具提供了文档编写、版本管理、主题定制等功能,有助于规范化文档管理。
  2. 测试规范化:对于单元测试、集成测试等,可以使用 Jest、Mocha、Karma 等测试框架 ,并结合 CI/CD 工具(如 Jenkins、Travis CI 等)进行自动化测试和报告。
  3. 版本管理规范化:可以使用 SemVer(语义化版本)规范,并结合工具如 standard-version 来自动化版本管理和发布流程。
  4. 代码审查规范化:可以使用工具如 GitHub、GitLab 等提供的 Pull Request 功能,结 合代码审查工具如 CodeStream、Crucible 等进行代码审查。
  5. 项目结构规范化:可以使用工具如 Yeoman、create-react-app 等来生成项目脚手架, 以确保项目结构的一致性。
  6. 构建和部署规范化:可以使用工具如 Webpack、Rollup 等进行项目构建,结合 CI/CD 工具(如 Jenkins、Travis CI、CircleCI 等)进行自动化构建和部署。

代码规范化

Eslint 可以帮助我们对当前项目的代码风格进行统一的检查。eslint 是一个开源的 JavaScriptlinting 工具,使用 espreeJavaScript 代码解析成抽象语法 树 (AST),然后通过AST 来分析我们代码,从而给予我们两种提示:

  • 代码质量问题:使用方式有可能有问题(problematic patterns)
  • 代码风格问题:风格不符合一定规则 (doesn’t adhere to certain style guidelines)。

一般来说我们自己也有给 vscode 安装 eslint 插件,为什么我们需要单独在项目中集成呢 ?就是因为每个人的 eslint 插件的配置都不一样,就会导致代码规范化得不统一。

安装

shell
pnpm install eslint -D
pnpm install eslint -D

初始化

shell
npx eslint --init
npx eslint --init

配置流程

运行上述初始化命令后就会在控制台上根据提示配置 eslint 了,配置完成后会生 成.eslintc.js文件(选择配置文件输出到 js 中)。当然也可以配置 .eslintignore 来新增不想格式化的文件。规则类似于 .gitignore

? How would you like to use ESLint?(你要如何使用 ESlint?) ...

To check syntax only (仅检查语法)

To check syntax and find problems(检查语法并查找问题)

To check syntax, find problems, and enforce code style(检查语法、查找问题和强制 执行代码样式)

? What type of modules does your project use?(你的项目使用的模块化标准是?) ...

JavaScript modules (import/export)

CommonJS (require/exports)

None of these

? Which framework does your project use?(你的项目使用了那种框架?) ...

React

Vue.js

None of these

? Does your project use TypeScript? (使用了 ts?)

No / Yes

? Where does your code run? (项目的运行环境是?)...

√ Browser √ Node

? What format do you want your config file to be in? (eslint 的配置文件生成在哪里?)...

JavaScript

YAML

JSON

使用

shell
pnpm eslint . 校验全部文件
pnpm eslint ./index.js 校验某个文件
pnpm eslint . 校验全部文件
pnpm eslint ./index.js 校验某个文件

自定义规则

​ 查看 eslint 官网进行配置项目规范化规则 ,点我

支持 Prettier

ESlint 也用 prettier 的规则来检测代码是否合法。下载 eslint-plugin-prettier eslint-config-prettier

  1. 安装
shell
npm add -D eslint-config-prettier #eslint兼容的插件
npm add -D eslint-plugin-prettier #eslint的prettier
npm add -D eslint-config-prettier #eslint兼容的插件
npm add -D eslint-plugin-prettier #eslint的prettier
  1. 修改.eslintrc.js 文件:
js
// .eslintrc.js
module.exports = {
  "extends": {
    // ...
    "prettier",
    "plugin:prettier/recommended"
  }
}
// .eslintrc.js
module.exports = {
  "extends": {
    // ...
    "prettier",
    "plugin:prettier/recommended"
  }
}

代码风格工具

​ 一般来说我们自己也有给 vscode 安装 Prettier 插件,为什么我们需要单独在项目中集 成呢?就是因为每个人的 Prettier 插件的配置都不一样,就会导致代码风格不统一。

安装

shell
pnpm install prettier eslint-config-prettier eslint-plugin-prettier -D
pnpm install prettier eslint-config-prettier eslint-plugin-prettier -D

注意

1.在.eslintrc 中,extend 中添加 "prettier" 解决 eslint 和 prettier 的冲突

​ 解决方法:因为 eslint-config-prettier 新版本更新之后,只需要写一个 "prettierr" 即可,无需多言指令。

配置

当我们安装好 prettier 后,可以进行测试,随意创建 test.js 文件,编写格式非常糟糕 的代码,然后运行:

shell
npx prettier --write .\test.js
pnpm exec prettier --write .\test.js
pnpm exec prettier . --write 格式化工程下的全部文件
npx prettier --write .\test.js
pnpm exec prettier --write .\test.js
pnpm exec prettier . --write 格式化工程下的全部文件

就会发现代码已经被格式化了,就说明安装成功了!

若需要自定义配置代码风格,则需要手动创建.prettierrc文件,当然也可以配置 .prettierignore 来新增不想格式化的文件。规则类似于 .gitignore。如下:

json
{
  "semi": true,
  "tabWidth": 2,
  "trailingComma": "none",
  "singleQuote": true,
  "arrowParens": "avoid"
}
{
  "semi": true,
  "tabWidth": 2,
  "trailingComma": "none",
  "singleQuote": true,
  "arrowParens": "avoid"
}

主要有以下项:

  • printWidth. 条件允许时每行字符长度大于该值时进行换行(prettier 不会强行换行 :比如将一个引号包裹的字符串折行)。默认为 80
  • tabWidth. 缩进空格数;默认为 2
  • semi. 语句末尾是否带分号
  • singleQuote. 是否将双引号转换为单引号。双引号里包含单引号时不会被格式化。
  • quoteProps. 对象属性引号的配置
  • jsxSingleQuote. jsx 文件里使用单引号
  • bracketSpacing. 圆括号之间添加空格,如{ a: b }
  • arrowParens. 箭头函数,参数添加圆括号,如(x)=>y
  • parser. 指定解析器,我们一般不需要默认的就行

全部配置项:https://prettier.io/docs/en/options.html

样式检查工具

stylelint,是一个 CSS 规范化检查工具。

安装

shell
pnpm install stylelint stylelint-config-standard stylelint-config-prettier -D
pnpm install stylelint stylelint-config-standard stylelint-config-prettier -D

stylelint —— css 的 lint 工具

stylelint-config-standard —— 官方内置一些标准规则,搭配 extends 使用,可以检查 sass、less 或者 vue 中的 style 部分的代码。

stylelint-config-prettier —— 抹平与 prettier 的格式化冲突问题,搭配 extends 使用

配置

使用 stylelint 检测器需要一个配置对象,你可以使用三种方式来创建这个对象。

  • package.json 中的 stylelint 属性。
  • .stylelintrc.js文件
  • stylelint.config.js 文件输出的 js 对象

一旦发现它们中的任何一个,将不再继续进行查找,进行解析,将使用解析后的对象。 本 次使用的是.stylelintrc.js 文件来进行配置。

创建.sytlelintrc.js,并写入以下内容:

js
module.exports = {
  extends: "stylelint-config-standard",
};
module.exports = {
  extends: "stylelint-config-standard",
};

创建好后即可使用npx stylelint "**/*.css"来进行测试是否安装配置成功,也可以使 用npx stylelint "**/*.scss"来处理所有 scss 文件。

使用

安装官方文档的说法你可以按照以下方法运行 stylelint 检测样式代码。

--fix 用来自动修复,但不能修复所有的问题,注意只能检查 css 文件。

json
// package.json
"scripts":{
  "lint:css":"stylelint src/**/*.css --fix",
  "lint:css":"stylelint 你的文件夹 --fix",
}
// package.json
"scripts":{
  "lint:css":"stylelint src/**/*.css --fix",
  "lint:css":"stylelint 你的文件夹 --fix",
}

自定义 CSS 属性顺序

想让 stylelint 帮我们为 css 属性排序?比如让宽高排在最前面?不妨试 试stylelint-order是用来在格式化 css 文件时对代码的属性进行排序。

安装

shell
pnpm install stylelint-order -D
pnpm install stylelint-order -D

配置

​ 在stylelintrc.js中配置:

js
module.exports = {
  // 为stylelint安装stylelint-order插件
  plugins: ["stylelint-order"],
  extends: "stylelint-config-standard",
  rules: {
    "order/properties-order": [
      // 规则顺序,可以自己随意定义
      "position",
      "top",
      "right",
      "bottom",
      "left",
      "z-index",
      "display",
      "float",
      "width",
      "height",
      "max-width",
      "max-height",
      "min-width",
      "min-height",
      "padding",
      "padding-top",
      "padding-right",
      "padding-bottom",
      "padding-left",
      "margin",
      "margin-top",
      "margin-right",
      "margin-bottom",
      "margin-left",
      "margin-collapse",
      "margin-top-collapse",
      "margin-right-collapse",
      "margin-bottom-collapse",
      "margin-left-collapse",
      "overflow",
      "overflow-x",
      "overflow-y",
      "clip",
      "clear",
      "font",
      "font-family",
      "font-size",
      "font-smoothing",
      "osx-font-smoothing",
      "font-style",
      "font-weight",
      "line-height",
      "letter-spacing",
      "word-spacing",
      "color",
      "text-align",
      "text-decoration",
      "text-indent",
      "text-overflow",
      "text-rendering",
      "text-size-adjust",
      "text-shadow",
      "text-transform",
      "word-break",
      "word-wrap",
      "white-space",
      "vertical-align",
      "list-style",
      "list-style-type",
      "list-style-position",
      "list-style-image",
      "pointer-events",
      "cursor",
      "background",
      "background-color",
      "border",
      "border-radius",
      "content",
      "outline",
      "outline-offset",
      "opacity",
      "filter",
      "visibility",
      "size",
      "transform",
    ],
  },
};
module.exports = {
  // 为stylelint安装stylelint-order插件
  plugins: ["stylelint-order"],
  extends: "stylelint-config-standard",
  rules: {
    "order/properties-order": [
      // 规则顺序,可以自己随意定义
      "position",
      "top",
      "right",
      "bottom",
      "left",
      "z-index",
      "display",
      "float",
      "width",
      "height",
      "max-width",
      "max-height",
      "min-width",
      "min-height",
      "padding",
      "padding-top",
      "padding-right",
      "padding-bottom",
      "padding-left",
      "margin",
      "margin-top",
      "margin-right",
      "margin-bottom",
      "margin-left",
      "margin-collapse",
      "margin-top-collapse",
      "margin-right-collapse",
      "margin-bottom-collapse",
      "margin-left-collapse",
      "overflow",
      "overflow-x",
      "overflow-y",
      "clip",
      "clear",
      "font",
      "font-family",
      "font-size",
      "font-smoothing",
      "osx-font-smoothing",
      "font-style",
      "font-weight",
      "line-height",
      "letter-spacing",
      "word-spacing",
      "color",
      "text-align",
      "text-decoration",
      "text-indent",
      "text-overflow",
      "text-rendering",
      "text-size-adjust",
      "text-shadow",
      "text-transform",
      "word-break",
      "word-wrap",
      "white-space",
      "vertical-align",
      "list-style",
      "list-style-type",
      "list-style-position",
      "list-style-image",
      "pointer-events",
      "cursor",
      "background",
      "background-color",
      "border",
      "border-radius",
      "content",
      "outline",
      "outline-offset",
      "opacity",
      "filter",
      "visibility",
      "size",
      "transform",
    ],
  },
};

忽略 stylelint 对 css 的检验

  1. 忽略整个文件,在首行加入 /* stylelint-disable */
css
/* stylelint-disable */
html {
}
/* stylelint-disable */
html {
}
  1. 忽略多行
css
/* stylelint-disable */
html {
}
.div {
  color: red;
}
/* stylelint-enable */
/* stylelint-disable */
html {
}
.div {
  color: red;
}
/* stylelint-enable */
  1. 忽略一行, 在样式前加入 /* stylelint-disable-next-line */ 以忽略该行
css
#id {
  /* stylelint-disable-next-line */
  color: pink !important;
}
#id {
  /* stylelint-disable-next-line */
  color: pink !important;
}
  1. .stylelintrc.js 內设定需要忽略的文件
js
{
  ignoreFiles: ["dist/**/*", "src/assets/scss/abc.scss"];
}
{
  ignoreFiles: ["dist/**/*", "src/assets/scss/abc.scss"];
}

git 规范

​ 在代码提交时,若项目代码没有按照格式化、规范化检查就提交到了仓库里面去,那岂不 是我们前面的配置不都没用了吗,所以就有了 git 规范。

​ 其中包含了:

  • husky
    • 操作 git 钩子的工具
  • lint-staged
    • 本地暂存代码检查工具
  • commitlint
    • commit 信息校验工具
  • commitizen
    • 辅助 commit 信息 ,就像这样,通过选择输入,规范提交信息

husky

​ husky 可以让我们在提交代码时做一些额外操作,如代码格式化,代码规范化检查,提交 注释是否符合规范等等功能。husky 就是基于 git hooks 在不同时间点执行不同的操作, 例如:

  • pre-commit:代码提交之前触发,可以通过此钩子判断代码是否符合规范。
  • commit-msg:对 commit 的信息校验,可以通过此钩子判定 commit 是否合法。
  • pre-push: 代码提交之前触发,可以通过此钩子对业务代码执行一些测试。

安装

shell
pnpm install -d husky
pnpm install -d husky

安装好后,执行npx husky install来初始化husky,执行之后则会创建.husky 文件夹 ,其中包含了一些基本的配置。在执行该命令前该仓库必须被 git 管理。

shell
npx husky install
npx husky install

为了保证其他开发者拉取代码时能够初始化 husky,由于 husky 只在本地起作用,所以我 们需要在 package.json 中添加该脚本,保证一安装项目依赖时保证 husky 被初始化。

只要执行pnpm install就会安装依赖,并执行prepare脚本,初始化 husky

json
{
  "scripts": {
    "prepare": "git init && husky install"
  }
}
{
  "scripts": {
    "prepare": "git init && husky install"
  }
}

git hooks

git hooks 的分类如下

  • 客户端 hooks
    • 提交工作流
      • pre-commit
      • prepare-commit-msg
      • commit-msg
      • post-commit
    • email 工作流
      • applypatch-msg
      • pre-applypatch
      • post-applypatch
    • 其它
      • pre-rebase
      • post-rewrite
      • post-checkout
      • post-merge
      • pre-push
      • pre-auto-gc
  • 服务器端 hooks
    • pre-receive
    • update
    • post-receive

使用

使用 husky 的时候,我们通常只关注 提交工作流 的几个 hooks,用得最多的一个是 pre-commit,pre-commit 会在本地 commit 时会触发该钩子。

使用 hosky 的时候,通常是用它来创建一系列的 git hooks,并在对应的文件中撰写 shell 脚本代码。

下面是官方示例中的一个,创建了 pre-commit hook 文件:

sheel
npx husky add .husky/pre-commit "npm test" # npm
pnpx husky add .husky/pre-commit "npm test" # pnpm
pnpx husky add .husky/pre-commit # 为空,可以自己到对应文件中编写
npx husky add .husky/pre-commit "npm test" # npm
pnpx husky add .husky/pre-commit "npm test" # pnpm
pnpx husky add .husky/pre-commit # 为空,可以自己到对应文件中编写

例如:

sh
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

# pnpm eslint 为自己编写的脚本,每当提交代码commit时就会执行该脚本中的内容。
pnpm eslint
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

# pnpm eslint 为自己编写的脚本,每当提交代码commit时就会执行该脚本中的内容。
pnpm eslint

lint-staged

​ lint-staged 只检查暂存区的文件。当我们使用 husky 的钩子执行某些操作时会发现 Perttier 会对项目所有的文件进行格式化,但起始我们仅仅只需要对有改动的文件进行检 查即可,因为贮存区中的文件早就被格式化过的代码,但依旧被校验就会很浪费时间,所以 lint-staged 可以帮助我们解决该问题。

安装

shell
 pnpm install -d lint-staged
 pnpm install -d lint-staged

修改 pre-commit 钩子文件(重要)

将 pre-commit 钩子执行的脚本替成npx lint-staged,这样lint-staged才会生效。

配置

下面的命令直接关系到npx lint-staged会执行哪些命令。

方法 1:

根目录下新建文件**.lintstagedrc.json**

json
//检验规则举例,具体检验什么文件哪些路径看团队需求
{
  //对src目录下所有文件校验
  "src/**/*.{js,cjs,ts,html,json,css,scss,vue}": ["npx prettier --write"],
  "src/**/*.{js,cjs,ts,vue}": ["npx eslint --fix"],
  //只对根目录的所有文件校验,不涉及文件夹
  "./*.{js,cjs,ts,html,json}": ["npx prettier --write"],
  "./*.{js,cjs,ts}": ["npx eslint --fix"]
}
//检验规则举例,具体检验什么文件哪些路径看团队需求
{
  //对src目录下所有文件校验
  "src/**/*.{js,cjs,ts,html,json,css,scss,vue}": ["npx prettier --write"],
  "src/**/*.{js,cjs,ts,vue}": ["npx eslint --fix"],
  //只对根目录的所有文件校验,不涉及文件夹
  "./*.{js,cjs,ts,html,json}": ["npx prettier --write"],
  "./*.{js,cjs,ts}": ["npx eslint --fix"]
}

方法 2:

直接在 package.json 添加如下对象

json
"lint-staged": {
    "src/**/*.{js,cjs,ts,html,json,css,scss,vue}": [
      "npx prettier --write"
    ],
    "src/**/*.{js,cjs,ts,vue}": [
      "npx eslint --fix"
    ],
    "./*.{js,cjs,ts,html,json}": [
      "npx prettier --write"
    ],
    "./*.{js,cjs,ts}": [
      "npx eslint --fix"
    ]
  },
"lint-staged": {
    "src/**/*.{js,cjs,ts,html,json,css,scss,vue}": [
      "npx prettier --write"
    ],
    "src/**/*.{js,cjs,ts,vue}": [
      "npx eslint --fix"
    ],
    "./*.{js,cjs,ts,html,json}": [
      "npx prettier --write"
    ],
    "./*.{js,cjs,ts}": [
      "npx eslint --fix"
    ]
  },

commitlint

commitlint 会对 git commit 中的注释部分进行检查,若不符合规范,禁止本次提交。

https://commitlint.js.org/#/guides-local-setup?id=install-commitlint

安装

shell
pnpm install --save-dev @commitlint/config-conventional @commitlint/cli
pnpm install --save-dev @commitlint/config-conventional @commitlint/cli

增加钩子

commit-msg 钩子执行 消息校验

shell
 npx husky add .husky/commit-msg 'npx commitlint --edit $1'
 npx husky add .husky/commit-msg 'npx commitlint --edit $1'

commitlint --edit <文件名>:执行 commitlint 命令行工具,并使用 --edit 选项, 从一个文件里提取 commit 内容来进行校验。校验规则由 commitlint.config.js 配置文 件来指定 ,reference-cli

$1:在新版的 husky 中 $HUSKY_GIT_PARAMS 变量已不再使用,取而代之是 $1文档地址

配置

由于上述钩子指定了会在提交代码时会执行npx commitlint --edit $1,commitlint 会 根据commitlint.config.js中的规则来检查消息是否规范,所以我们需要手动创 建commitlint.config.js文件。

js
module.exports = {
  // 规则将继承与@commitlint/config-conventional
  extends: ["@commitlint/config-conventional"],
};
module.exports = {
  // 规则将继承与@commitlint/config-conventional
  extends: ["@commitlint/config-conventional"],
};

同时需要修改 eslint 的配置项,若 eslint 设置了代码只会在浏览器中运行的话将不会支 持 cmd,所以需要增加 node 选项,否则 eslint 将无法通过。

js
// .eslintrc.js
module.exports = {
  env: {
    node: true,
    browser: true,
    es2021: true,
  },
};
// .eslintrc.js
module.exports = {
  env: {
    node: true,
    browser: true,
    es2021: true,
  },
};

当然也可以在 commitlint.config.js 中引入 eslint 注释即可。

js
/* eslint-env node */
module.exports = {
  // 规则将继承与@commitlint/config-conventional
  extends: ["@commitlint/config-conventional"],
};
/* eslint-env node */
module.exports = {
  // 规则将继承与@commitlint/config-conventional
  extends: ["@commitlint/config-conventional"],
};

默认提交规范

​ 配置好就可以尝试提交了,不过此时的提交检查是默认的检查规则,默认提交格式:

git commit -m <type>[optional scope]: <description> //注意冒号后面有空格
- type:提交的改动类型(如新增、修改、更新等)
- optional scope:标识此次提交主要涉及到代码中哪个模块
- description:一句话描述此次提交的主要内容
git commit -m <type>[optional scope]: <description> //注意冒号后面有空格
- type:提交的改动类型(如新增、修改、更新等)
- optional scope:标识此次提交主要涉及到代码中哪个模块
- description:一句话描述此次提交的主要内容

常用 type

type描述
feat新增功能
fixbug 修复
style不影响程序逻辑的代码修改(修改空白字符,补全缺失的分号等)
refactor重构代码(既没有新增功能,也没有修复 bug)
docs文档更新
test增加测试
chore构建过程或辅助工具的变动

例如:

shell
git commit -m 'feat: 增加 xxx 功能'
git commit -m 'bug: 修复 xxx 功能'
git commit -m 'feat: 增加 xxx 功能'
git commit -m 'bug: 修复 xxx 功能'

自定义提交规范

输入命令创建配置文件(在根目录)

shell
echo  "module.exports = {extends: ['@commitlint/config-conventional']}; "  > commitlint.config.js
echo  "module.exports = {extends: ['@commitlint/config-conventional']}; "  > commitlint.config.js

rule 配置

rule 由name配置数组组成,如:'name:[0, 'always', 72]'

数组第一位,参数设置错误级别

  • 0:disable
  • 1:warning
  • 2:error

数组第二位,是否应用

  • always
  • never

数组第三位,rule 的值

具体规则参考 👉 更多

关于配置文件 👉 更多

例子:

js
module.exports = {
  extends: ["@commitlint/config-conventional"],
  rules: {
    "type-case": [2, "always", ["lower-case", "upper-case"]],
    "type-enum": [
      2,
      "always",
      [
        "feat",
        "fix",
        "docs",
        "style",
        "refactor",
        "perf",
        "test",
        "chore",
        "revert",
      ],
    ],
  },
};
module.exports = {
  extends: ["@commitlint/config-conventional"],
  rules: {
    "type-case": [2, "always", ["lower-case", "upper-case"]],
    "type-enum": [
      2,
      "always",
      [
        "feat",
        "fix",
        "docs",
        "style",
        "refactor",
        "perf",
        "test",
        "chore",
        "revert",
      ],
    ],
  },
};

参考资料:

commitlint 文档

husky 文档

commitizen(非必须)

​ commitize 可以辅助我们设置代码提交的消息,他可以根据项目的提交规则来选择提交类 型,我们只需要写入消息即可。

安装

shell
// 1. 安装 commitizen
npm install commitizen -D

// 2.cz-conventional-changelog用来规范提交信息。
npm install cz-conventional-changelog -D
// 3.commitizen规范化提交标准 cz-conventional-changelog-zh中文版的提交规范提示
npm install cz-conventional-changelog-zh -D
// 1. 安装 commitizen
npm install commitizen -D

// 2.cz-conventional-changelog用来规范提交信息。
npm install cz-conventional-changelog -D
// 3.commitizen规范化提交标准 cz-conventional-changelog-zh中文版的提交规范提示
npm install cz-conventional-changelog-zh -D

配置

在 package.json 中增加一个对象,并增加一个脚本。以后提交代码时就可以不适用 git commit 了,而是运行 npm run commit 使用 commitize 辅助我们提交代码。

json
"script":{
	"commit":"git-cz"
},
"config": {
    "commitizen": {
      // 英文版本
      "path": "./node_modules/cz-conventional-changelog",
      // 中文版本
      "path": "./node_modules/cz-conventional-changelog-zh"
    }
  }
"script":{
	"commit":"git-cz"
},
"config": {
    "commitizen": {
      // 英文版本
      "path": "./node_modules/cz-conventional-changelog",
      // 中文版本
      "path": "./node_modules/cz-conventional-changelog-zh"
    }
  }

使用

​ 当运行npm run commit时,则会执行 git-cz 命令,输出一个交互框辅助我们生成提交 信息。

(1)选择提交类型

(2)本修改影响的是内容(范围)?可以填文件名

​ 若写入了内容,则会在 type 后生成作用域名称。例如 feat(user): test

(3)写一个简短的介绍

(4)提供一个长的介绍

(5)本修改是否实现了某个 issues?

changelog

使用conventional-changelog-cli 生成提交日志,可以快速的浏览提交记录中的所有 信息。

安装

shell
pnpm i -D conventional-changelog-cli
# 根目录下在创建CHANGELOG.md文件
echo "" > CHANGELOG.md
pnpm i -D conventional-changelog-cli
# 根目录下在创建CHANGELOG.md文件
echo "" > CHANGELOG.md

配置

在 package.json 中新增脚本:

shell
{
	"script":{
		"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s"
	}
}
{
	"script":{
		"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s"
	}
}

使用

首次执行:

conventional-changelog -p angular -i CHANGELOG.md -s -r 0
conventional-changelog -p angular -i CHANGELOG.md -s -r 0

执行:

shell
pnpm run changelog
pnpm run changelog

在 vite 中集成规范化

eslint

安装

安装后,依旧使用npx eslint install来初始化 eslint 配置项以及安装相关插件。

集成 vite

让 eslint 相关报错出现在 vite 项目的错误窗口中。

  1. 安装:
shell
npm install -D vite-plugin-eslint @babel/core @babel/eslint-parser
npm install -D vite-plugin-eslint @babel/core @babel/eslint-parser
  1. 配置 vite.config.ts 文件
ts
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import eslintPlugin from "vite-plugin-eslint";

export default defineConfig({
  plugins: [
    vue(),
    eslintPlugin({
      include: ["src/**/*.ts", "src/**/*.vue", "src/*.ts", "src/*.vue"],
    }),
  ],
});
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import eslintPlugin from "vite-plugin-eslint";

export default defineConfig({
  plugins: [
    vue(),
    eslintPlugin({
      include: ["src/**/*.ts", "src/**/*.vue", "src/*.ts", "src/*.vue"],
    }),
  ],
});

增加脚本

在 package.json 中添加该命令:

json
"lint:eslint": "eslint . --fix",
"lint:eslint": "eslint . --fix",

prettier

安装

shell
npm install -D prettier
npm install -D eslint-config-prettier #eslint兼容的插件
npm install -D eslint-plugin-prettier #eslint的prettier
npm install -D prettier
npm install -D eslint-config-prettier #eslint兼容的插件
npm install -D eslint-plugin-prettier #eslint的prettier

配置

在根目录下面添加.prettierrc.cjs文件夹,然后将下面的配置添加到其中。

js
/** .prettierrc.js
 * 在VSCode中安装prettier插件 打开插件配置填写`.prettierrc.js` 将本文件作为其代码格式化规范
 * 在本文件中修改格式化规则,不会同时触发改变ESLint代码检查,所以每次修改本文件需要重启VSCode,ESLint检查才能同步代码格式化
 * 需要相应的代码格式化规范请自行查阅配置,下面为默认项目配置
 */
module.exports = {
  // 一行最多多少个字符
  printWidth: 150,
  // 指定每个缩进级别的空格数
  tabWidth: 2,
  // 使用制表符而不是空格缩进行
  useTabs: true,
  // 在语句末尾是否需要分号
  semi: true,
  // 是否使用单引号
  singleQuote: true,
  // 更改引用对象属性的时间 可选值"<as-needed|consistent|preserve>"
  quoteProps: "as-needed",
  // 在JSX中使用单引号而不是双引号
  jsxSingleQuote: false,
  // 多行时尽可能打印尾随逗号。(例如,单行数组永远不会出现逗号结尾。) 可选值"<none|es5|all>",默认none
  trailingComma: "es5",
  // 在对象文字中的括号之间打印空格
  bracketSpacing: true,
  // jsx 标签的反尖括号需要换行
  jsxBracketSameLine: false,
  // 在单独的箭头函数参数周围包括括号 always:(x) => x \ avoid:x => x
  arrowParens: "always",
  // 这两个选项可用于格式化以给定字符偏移量(分别包括和不包括)开始和结束的代码
  rangeStart: 0,
  rangeEnd: Infinity,
  // 指定要使用的解析器,不需要写文件开头的 @prettier
  requirePragma: false,
  // 不需要自动在文件开头插入 @prettier
  insertPragma: false,
  // 使用默认的折行标准 always\never\preserve
  proseWrap: "preserve",
  // 指定HTML文件的全局空格敏感度 css\strict\ignore
  htmlWhitespaceSensitivity: "css",
  // Vue文件脚本和样式标签缩进
  vueIndentScriptAndStyle: false,
  //在 windows 操作系统中换行符通常是回车 (CR) 加换行分隔符 (LF),也就是回车换行(CRLF),
  //然而在 Linux 和 Unix 中只使用简单的换行分隔符 (LF)。
  //对应的控制字符为 "\n" (LF) 和 "\r\n"(CRLF)。auto意为保持现有的行尾
  // 换行符使用 lf 结尾是 可选值"<auto|lf|crlf|cr>"
  endOfLine: "auto",
};
/** .prettierrc.js
 * 在VSCode中安装prettier插件 打开插件配置填写`.prettierrc.js` 将本文件作为其代码格式化规范
 * 在本文件中修改格式化规则,不会同时触发改变ESLint代码检查,所以每次修改本文件需要重启VSCode,ESLint检查才能同步代码格式化
 * 需要相应的代码格式化规范请自行查阅配置,下面为默认项目配置
 */
module.exports = {
  // 一行最多多少个字符
  printWidth: 150,
  // 指定每个缩进级别的空格数
  tabWidth: 2,
  // 使用制表符而不是空格缩进行
  useTabs: true,
  // 在语句末尾是否需要分号
  semi: true,
  // 是否使用单引号
  singleQuote: true,
  // 更改引用对象属性的时间 可选值"<as-needed|consistent|preserve>"
  quoteProps: "as-needed",
  // 在JSX中使用单引号而不是双引号
  jsxSingleQuote: false,
  // 多行时尽可能打印尾随逗号。(例如,单行数组永远不会出现逗号结尾。) 可选值"<none|es5|all>",默认none
  trailingComma: "es5",
  // 在对象文字中的括号之间打印空格
  bracketSpacing: true,
  // jsx 标签的反尖括号需要换行
  jsxBracketSameLine: false,
  // 在单独的箭头函数参数周围包括括号 always:(x) => x \ avoid:x => x
  arrowParens: "always",
  // 这两个选项可用于格式化以给定字符偏移量(分别包括和不包括)开始和结束的代码
  rangeStart: 0,
  rangeEnd: Infinity,
  // 指定要使用的解析器,不需要写文件开头的 @prettier
  requirePragma: false,
  // 不需要自动在文件开头插入 @prettier
  insertPragma: false,
  // 使用默认的折行标准 always\never\preserve
  proseWrap: "preserve",
  // 指定HTML文件的全局空格敏感度 css\strict\ignore
  htmlWhitespaceSensitivity: "css",
  // Vue文件脚本和样式标签缩进
  vueIndentScriptAndStyle: false,
  //在 windows 操作系统中换行符通常是回车 (CR) 加换行分隔符 (LF),也就是回车换行(CRLF),
  //然而在 Linux 和 Unix 中只使用简单的换行分隔符 (LF)。
  //对应的控制字符为 "\n" (LF) 和 "\r\n"(CRLF)。auto意为保持现有的行尾
  // 换行符使用 lf 结尾是 可选值"<auto|lf|crlf|cr>"
  endOfLine: "auto",
};

增加脚本

在 package.json 中添加该命令:

json
"lint:prettier": "prettier . --write --fix",
"lint:prettier": "prettier . --write --fix",

eslint+prettier

配置完成prettier肯定会和eslint发生冲突,所以接下来要调整一下.eslintrc.js文 件,通过几个扩展,来完成vue3、ts、prettier的规则和eslint插件结合使用,配置如 下面代码所示。 Vue3 的 setup 语法糖中有几个宏定义,如果不声明直接引用会报错,这 里可以在配置文件中加入globals配置项(如下所示),通过全局声明这几个宏定义,就 可以直接使用这几个函数不用再提前声明了,eslint检查也会正常通过。 可以看到配置 文件中有process.env.NODE_ENV,这是一个node环境变量,使用过程可能会报错,这里 安装@types/node(npm i -D @types/node)插件,就可以在全局使用process这个参数 了,我们这里主要用于区分开发和生产环境,下面配置就是开发环境允许使 用console.log(),而生产环境不能使用,如果构建包的过程中代码含 有console.log(),会导致构建失败,请删除 log 后再打包。

js
module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true,
  },
  extends: [
    "eslint-config-prettier",
    "eslint:recommended", // 使用推荐的eslint
    "plugin:@typescript-eslint/recommended",
    "plugin:vue/vue3-recommended", // 使用插件支持vue3
    "plugin:vue/vue3-essential",
    // 1.继承.prettierrc.js文件规则
    // 2.开启rules的 "prettier/prettier": "error"
    // 3.eslint fix的同时执行prettier格式化
    "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"],
  rules: {},
};
module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true,
  },
  extends: [
    "eslint-config-prettier",
    "eslint:recommended", // 使用推荐的eslint
    "plugin:@typescript-eslint/recommended",
    "plugin:vue/vue3-recommended", // 使用插件支持vue3
    "plugin:vue/vue3-essential",
    // 1.继承.prettierrc.js文件规则
    // 2.开启rules的 "prettier/prettier": "error"
    // 3.eslint fix的同时执行prettier格式化
    "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"],
  rules: {},
};

stylelint

​ 在 vite+vue+scss 项目中集成 stylelint 可以帮助我们格式化 css 代码、设置 css 属 性的排序规则。

安装

shell
pnpm install stylelint stylelint-config-html stylelint-config-recommended-scss stylelint-config-recommended-vue stylelint-config-standard stylelint-config-standard-scss stylelint-config-recess-order postcss postcss-html stylelint-config-prettier -D
pnpm install stylelint stylelint-config-html stylelint-config-recommended-scss stylelint-config-recommended-vue stylelint-config-standard stylelint-config-standard-scss stylelint-config-recess-order postcss postcss-html stylelint-config-prettier -D

说明:

stylelint:stylelint 核心库

stylelint-config-htmlStylelint :的可共享 HTML(和类似 HTML)配置,捆绑 postcss-html 并对其进行配置。

stylelint-config-recommended-scss:扩展 stylelint-config-recommended 共享配置, 并为 SCSS 配置其规则

stylelint-config-recommended-vue:扩展 stylelint-config-recommended 共享配置,并 为 Vue 配置其规则

stylelint-config-standard:打开额外的规则来执行在规范和一些 CSS 样式指南中发现的 通用约定,包括:惯用 CSS 原则,谷歌的 CSS 样式指南,Airbnb 的样式指南,和 @mdo 的代码指南。

stylelint-config-standard-scss:扩展 stylelint-config-standard 共享配置,并为 SCSS 配置其规则

stylelint-config-recess-order:属性的排序(插件包)

stylelint-config-prettier:关闭所有不必要的或可能与 Prettier 冲突的规则

postcss:postcss-html 的依赖包

postcss-html:用于解析 HTML(和类似 HTML)的 PostCSS 语法

配置

修改 package.json 中相关配置:

在 script 中增加命令:

json
"lint:style": "stylelint \"./**/*.{css,less,scss,vue,html}\" --fix"
"lint:style": "stylelint \"./**/*.{css,less,scss,vue,html}\" --fix"

在 lint-staged 中增加需要检查的文件,并配置对应需要执行的命令:

diff
"lint-staged": {
+		"src/**/*.{html,less,css,scss,vue}": [
+			"pnpm run lint:style"
+		],
		"src/**/*.{js,cjs,ts,html,json,css,scss,vue}": [
			"npx prettier --write"
		],
		"src/**/*.{js,cjs,ts,vue}": [
			"npx eslint --fix"
		],
		"./*.{js,cjs,ts,html,json}": [
			"npx prettier --write"
		],
		"./*.{js,cjs,ts}": [
			"npx eslint --fix"
		]
	},
"lint-staged": {
+		"src/**/*.{html,less,css,scss,vue}": [
+			"pnpm run lint:style"
+		],
		"src/**/*.{js,cjs,ts,html,json,css,scss,vue}": [
			"npx prettier --write"
		],
		"src/**/*.{js,cjs,ts,vue}": [
			"npx eslint --fix"
		],
		"./*.{js,cjs,ts,html,json}": [
			"npx prettier --write"
		],
		"./*.{js,cjs,ts}": [
			"npx eslint --fix"
		]
	},

路径别名

路径别名可以说是项目必要的配置了,可以方便我们读取某个文件路径。在 vite 项目中配 置项目别名只需要在 vite.config.js 中定义即可,若是 ts 项目需要在 ts.config.json 中配置才能获得编辑器的支持。

vite.config.js

diff
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "node:path";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
+  resolve: {
+    alias: {
+      "@": path.resolve(__dirname, "src"),
+      "@User": path.resolve(__dirname, "src/views/user"), // 其他别名
+      "@Admin": path.resolve(__dirname, "src/views/admin"),// 其他别名
+    },
+  },
});
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "node:path";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
+  resolve: {
+    alias: {
+      "@": path.resolve(__dirname, "src"),
+      "@User": path.resolve(__dirname, "src/views/user"), // 其他别名
+      "@Admin": path.resolve(__dirname, "src/views/admin"),// 其他别名
+    },
+  },
});

ts.config.json

diff
{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "skipLibCheck": true,

    /* Bundler mode */
+    "baseUrl": ".",
+    "paths": {
+      "@/*": ["src/*"],
+      "@User/*": ["src/views/user/*"],
+      "@Admin/*": ["src/views/admin/*"],
+    },
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve",

    /* Linting */
    "strict": true,
    "noUnusedLocals": false,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
  "references": [{ "path": "./tsconfig.node.json" }]
}
{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "skipLibCheck": true,

    /* Bundler mode */
+    "baseUrl": ".",
+    "paths": {
+      "@/*": ["src/*"],
+      "@User/*": ["src/views/user/*"],
+      "@Admin/*": ["src/views/admin/*"],
+    },
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve",

    /* Linting */
    "strict": true,
    "noUnusedLocals": false,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
  "references": [{ "path": "./tsconfig.node.json" }]
}