Some rules that should be configured when the front-end develops multi-person collaborative team projects

This article mainly records some pre-configurations that the team needs to do to develop a front-end project, such as Eslint syntax checking, prettierrc formatting rules, and rules when submitting code, etc.

Table of contents

1. Build the project

 2.Eslint configuration (code inspection tool)

2.1 Install Eslint

2.2 Configure Eslint 

2.3.eslintignore ignore files (ignore files that do not need to be checked)

2.4 Add running script

3. Configure prettier formatting

 3.1 Dependencies required for installation

3.2.prettierrc.json add rules

3.3 .prettierignore ignore files

 4. Configure stylelint

4.1 Configuration

4.2 Ignoring files

4.3 Add running script

4.4 Using formatting

 5. Configure husky

 6. Configure commitlint

 7. Mandatory Unity Package Manager Tools


The project structure I built is: Vue3 + Ts + Vite + scss

Compiler used: WebStorm

Package management tool: pnpm

1. Build the project

The reason for choosing pnpm is because it has more advantages than some similar package managers: such as faster speed, smaller memory, etc.

When using pnpm for the first time, you need to install it globally

npm i -g pnpm

Initialize the project

pnpm create vite

Then choose the project you need

Preliminary configuration: Let the project automatically open the browser when it starts, without manually opening it

Add --open to the startup project configuration in the package.json file

 2.Eslint configuration (code inspection tool)

Introduction: ESLint was originally an open source project created by Nicholas C. Zakas  in June 2013. Its goal is to provide a plug-in javascript code detection tool.

2.1 Install Eslint

first time installation

pnpm i eslint -D

Generate configuration file: .eslint.cjs

npx eslint --init

Select configuration:

 Next, I will ask if I need to download some plug-ins for checking vue grammar and ts grammar, just select Yes

 Then you will be asked what package manager tool you are using, just choose according to yourself

2.2 Configure Eslint 

Next, a configuration file will succeed

module.exports = {
    //运行环境
    "env": {
        "browser": true,//浏览器端
        "es2021": true,//es2021
    },
    //规则继承
    "extends": [
        //全部规则默认是关闭的,这个配置项开启推荐规则,推荐规则参照文档
        //比如:函数不能重名、对象不能出现重复key
        "eslint:recommended",
        //vue3语法规则
        "plugin:vue/vue3-essential",
        //ts语法规则
        "plugin:@typescript-eslint/recommended"
    ],
    //要为特定类型的文件指定处理器
    "overrides": [
    ],
    //指定解析器:解析器
    //Esprima 默认解析器
    //Babel-ESLint babel解析器
    //@typescript-eslint/parser ts解析器
    "parser": "@typescript-eslint/parser",
    //指定解析器选项
    "parserOptions": {
        "ecmaVersion": "latest",//校验ECMA最新版本
        "sourceType": "module"//设置为"script"(默认),或者"module"代码在ECMAScript模块中
    },
    //ESLint支持使用第三方插件。在使用插件之前,您必须使用npm安装它
    //该eslint-plugin-前缀可以从插件名称被省略
    "plugins": [
        "vue",
        "@typescript-eslint"
    ],
    //eslint规则
    "rules": {
    }
}

Detailed configuration options can be configured according to your own project needs, refer to the official website: ESLint - Pluggable JavaScript linter - ESLint Chinese

 Install the plug-in for Vue3 environment code inspection (according to your own project requirements)

# 让所有与prettier规则存在冲突的Eslint rules失效,并使用prettier进行代码检查
"eslint-config-prettier": "^8.6.0",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-node": "^11.1.0",
# 运行更漂亮的Eslint,使prettier规则优先级更高,Eslint优先级低
"eslint-plugin-prettier": "^4.2.1",
# vue.js的Eslint插件(查找vue语法错误,发现错误指令,查找违规风格指南
"eslint-plugin-vue": "^9.9.0",
# 该解析器允许使用Eslint校验所有babel code
"@babel/eslint-parser": "^7.19.1",

Install the plugin:

pnpm install -D eslint-plugin-import eslint-plugin-vue eslint-plugin-node eslint-plugin-prettier eslint-config-prettier eslint-plugin-node @babel/eslint-parser

Modify the .eslintrc.cjs configuration file:


module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true,
    jest: true,
  },
  /* 指定如何解析语法 */
  parser: 'vue-eslint-parser',
  /** 优先级低于 parse 的语法解析配置 */
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module',
    parser: '@typescript-eslint/parser',
    jsxPragma: 'React',
    ecmaFeatures: {
      jsx: true,
    },
  },
  /* 继承已有的规则 */
  extends: [
    'eslint:recommended',
    'plugin:vue/vue3-essential',
    'plugin:@typescript-eslint/recommended',
    'plugin:prettier/recommended',
  ],
  plugins: ['vue', '@typescript-eslint'],
  /*
   * "off" 或 0    ==>  关闭规则
   * "warn" 或 1   ==>  打开的规则作为警告(不影响代码执行)
   * "error" 或 2  ==>  规则作为一个错误(代码不能执行,界面报错)
   */
  rules: {
    // eslint(https://eslint.bootcss.com/docs/rules/)
    'no-var': 'error', // 要求使用 let 或 const 而不是 var
    'no-multiple-empty-lines': ['warn', { max: 1 }], // 不允许多个空行
    'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    'no-unexpected-multiline': 'error', // 禁止空余的多行
    'no-useless-escape': 'off', // 禁止不必要的转义字符

    // typeScript (https://typescript-eslint.io/rules)
    '@typescript-eslint/no-unused-vars': 'error', // 禁止定义未使用的变量
    '@typescript-eslint/prefer-ts-expect-error': 'error', // 禁止使用 @ts-ignore
    '@typescript-eslint/no-explicit-any': 'off', // 禁止使用 any 类型
    '@typescript-eslint/no-non-null-assertion': 'off',
    '@typescript-eslint/no-namespace': 'off', // 禁止使用自定义 TypeScript 模块和命名空间。
    '@typescript-eslint/semi': 'off',

    // eslint-plugin-vue (https://eslint.vuejs.org/rules/)
    'vue/multi-word-component-names': 'off', // 要求组件名称始终为 “-” 链接的单词
    'vue/script-setup-uses-vars': 'error', // 防止<script setup>使用的变量<template>被标记为未使用
    'vue/no-mutating-props': 'off', // 不允许组件 prop的改变
    'vue/attribute-hyphenation': 'off', // 对模板中的自定义组件强制执行属性命名样式
  },
}

Inspection rules reference official website

2.3.eslintignore ignore files (ignore files that do not need to be checked)

Create a new file in the project directory: .eslintignore

Fill in documents that do not require inspection

dist
node_modeles

2.4 Add running script

package.json adds two running scripts

"scripts": {
    "lint": "eslint src", //运行此脚本进行语法检查
    "fix": "eslint src --fix", //运行此脚本进行语法纠正
}

Test whether the script can run, we can add some other codes that do not meet our rules

 

Our rules explicitly configure that var cannot be used, and now we can run it to see if there are any errors

 

This is also an error checked out, we can run the command to correct it

 

3. Configure prettier formatting

One of eslint and prettier guarantees the quality of js code, and the other guarantees the beauty of code.

 3.1 Dependencies required for installation

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

3.2.prettierrc.json add rules

Add a configuration file in the project directory: .prettierrc.json

Here are some formatting rules: For specific requirements, please refer to the official website: Prettier Chinese website Prettier is an "attitude" code formatting tool

{
  "singleQuote": true,  //要求字符串都是单引号
  "semi": false, //要求结尾没有双引号
  "bracketSpacing": true, //
  "htmlWhitespaceSensitivity": "ignore",
  "endOfLine": "auto",
  "trailingComma": "all",
  "tabWidth": 2 //缩进格子
}

3.3 .prettierignore ignore files

Create a new file in the project directory

add rule

/dist/*
/html/*
.local
/node_modules/**
**/*.svg
**/*.sh
/public/*

Test whether the formatting rules are in effect

Here's the code without formatting:

 Run pnpm run lint to check

It can find our mistakes according to the rules

 Run pnpm run fix to fix

 corrected code

 4. Configure stylelint

stylelint is a lint tool for css. It can format css code, check css syntax errors and unreasonable writing, specify css writing order, etc.

I use scss syntax, you can do it according to your own needs, refer to the official website: There are corresponding plug-ins and tutorials Home | Stylelint Chinese Documentation | Stylelint Chinese Website

4.1 Configuration

Installation dependencies:

pnpm add sass sass-loader stylelint postcss postcss-scss postcss-html stylelint-config-prettier stylelint-config-recess-order stylelint-config-recommended-scss stylelint-config-standard stylelint-config-standard-vue stylelint-scss stylelint-order stylelint-config-standard-scss -D

Add configuration file:.stylelintrc.cjs

配置项:

// @see https://stylelint.bootcss.com/

module.exports = {
  extends: [
    'stylelint-config-standard', // 配置stylelint拓展插件
    'stylelint-config-html/vue', // 配置 vue 中 template 样式格式化
    'stylelint-config-standard-scss', // 配置stylelint scss插件
    'stylelint-config-recommended-vue/scss', // 配置 vue 中 scss 样式格式化
    'stylelint-config-recess-order', // 配置stylelint css属性书写顺序插件,
    'stylelint-config-prettier', // 配置stylelint和prettier兼容
  ],
  overrides: [
    {
      files: ['**/*.(scss|css|vue|html)'],
      customSyntax: 'postcss-scss',
    },
    {
      files: ['**/*.(html|vue)'],
      customSyntax: 'postcss-html',
    },
  ],
  ignoreFiles: [
    '**/*.js',
    '**/*.jsx',
    '**/*.tsx',
    '**/*.ts',
    '**/*.json',
    '**/*.md',
    '**/*.yaml',
  ],
  /**
   * null  => 关闭该规则
   * always => 必须
   */
  rules: {
    'value-keyword-case': null, // 在 css 中使用 v-bind,不报错
    'no-descending-specificity': null, // 禁止在具有较高优先级的选择器后出现被其覆盖的较低优先级的选择器
    'function-url-quotes': 'always', // 要求或禁止 URL 的引号 "always(必须加上引号)"|"never(没有引号)"
    'no-empty-source': null, // 关闭禁止空源码
    'selector-class-pattern': null, // 关闭强制选择器类名的格式
    'property-no-unknown': null, // 禁止未知的属性(true 为不允许)
    'block-opening-brace-space-before': 'always', //大括号之前必须有一个空格或不能有空白符
    'value-no-vendor-prefix': null, // 关闭 属性值前缀 --webkit-box
    'property-no-vendor-prefix': null, // 关闭 属性前缀 -webkit-mask
    'selector-pseudo-class-no-unknown': [
      // 不允许未知的选择器
      true,
      {
        ignorePseudoClasses: ['global', 'v-deep', 'deep'], // 忽略属性,修改element默认样式的时候能使用到
      },
    ],
  },
}

4.2 Ignoring files

Add file: .stylelintignore

Documents that do not require inspection:

/node_modules/*
/dist/*
/html/*
/public/*

4.3 Add running script

 "scripts": {
    "dev": "vite --open",
    "build": "vue-tsc && vite build",
    "preview": "vite preview",
    "lint": "eslint src",
    "fix": "eslint src --fix",
    //这下面的三个
    "format": "prettier --write \"./**/*.{html,vue,ts,js,json,md}\"",
    "lint:eslint": "eslint src/**/*.{ts,vue} --cache --fix",
    "lint:style": "stylelint src/**/*.{css,scss,vue} --cache --fix"
  },

4.4 Using formatting

This is the corresponding vue file without formatting

 Run: pnpm run format to correct

 5. Configure husky

We have integrated our code verification tool above, but we need to manually execute the command every time to format our code. If someone submits to the remote repository without formatting, then this specification is useless. So we need to force developers to submit according to code specifications.

 To do this, we need to use husky to trigger the git hook (git's hook on the client side) before the code is submitted, and then execute it pnpm run formatto automatically format our code.

Let's take the github repository as an example:

When we submit unformatted code, it can be submitted normally:

Therefore, when the team collaborates to develop a project, we need to force formatting before submitting the code 

install husky

pnpm install -D husky

Add configuration file:

npx husky-init

 

 Modify the configuration file: This means that this command will be automatically executed when you submit the code. This is the formatted code file

 We can try to submit the code again: the code is

 6. Configure commitlint

For our commit information (remarks when submitting code), there is also a unified specification, which cannot be written casually. To make everyone implement it according to a unified standard, we can use commitlint to achieve it .

Install:

pnpm add @commitlint/config-conventional @commitlint/cli -D

Add a configuration file and create a new one commitlint.config.cjs(note that it is cjs)

Add the corresponding rule:

module.exports = {
  extends: ['@commitlint/config-conventional'],
  // 校验规则
  rules: {
    'type-enum': [
      2,
      'always',
      [
       'feat',//新特性、新功能
        'fix',//修改bug
        'docs',//文档修改
        'style',//代码格式修改, 注意不是 css 修改
        'refactor',//代码重构
        'perf',//优化相关,比如提升性能、体验
        'test',//测试用例修改
        'chore',//其他修改, 比如改变构建流程、或者增加依赖库、工具等
        'revert',//回滚到上一个版本
        'build',//编译相关的修改,例如发布版本、对项目构建或者依赖的改动
      ],
    ],
    'type-case': [0],
    'type-empty': [0],
    'scope-empty': [0],
    'scope-case': [0],
    'subject-full-stop': [0, 'never'],
    'subject-case': [0, 'never'],
    'header-max-length': [0, 'always', 72],
  },
}

package.jsonConfigure the scripts command in

# 在scrips中添加下面的代码
{
"scripts": {
    "commitlint": "commitlint --config commitlint.config.cjs -e -V"
  },
}

The main thing to pay attention to is the comment information of the submission rules in the configuration file: you need to make a note when submitting the code

'feat',//新特性、新功能
'fix',//修改bug
'docs',//文档修改
'style',//代码格式修改, 注意不是 css 修改
'refactor',//代码重构
'perf',//优化相关,比如提升性能、体验
'test',//测试用例修改
'chore',//其他修改, 比如改变构建流程、或者增加依赖库、工具等
'revert',//回滚到上一个版本
'build',//编译相关的修改,例如发布版本、对项目构建或者依赖的改动

Automatically configure husky, execute it when executing the git command, and install the configuration file

npx husky add .husky/commit-msg

 Next, you can try to submit the code, and you will be reminded that you cannot submit the code, and you need to add keywords in the rules

 The submission can be successful only by running with keywords:

 7. Mandatory Unity Package Manager Tools

When the team develops a project, it is necessary to unify the package manager tool, because different package manager tools download the same dependency, and the version may be different, resulting in bugs in the project, so the package manager tool needs to be managed uniformly! ! !

Create a file in the root directory scritps/preinstall.js, add the following content, you can refer to the official website for configuration

if (!/pnpm/.test(process.env.npm_execpath || '')) {
  console.warn(
    `\u001b[33mThis repository must using pnpm as the package manager ` +
    ` for scripts to work properly.\u001b[39m\n`,
  )
  process.exit(1)
}

Configuration naming:

"scripts": {
	"preinstall": "node ./scripts/preinstall.js"
}

After this configuration, we can only use pnpm to download the package, and we cannot download it with other tools

The above are the things that should be configured when the team develops and collaborates, and the rules that need to be followed

Guess you like

Origin blog.csdn.net/m0_64642443/article/details/131800907