天天看点

前端h5项目统一代码风格配置(eslint + stylelint + prettier + lint-staged)一、概述二、editorConfig三、eslint四、stylelint五、prettier六、husky + lint-staged七、typeScript 校验

2021-12-28 更新

husky

v7 版本的配置方式已经完全改变,官方地址,配置方式:

  • package.json

    的scripts里添加命令:
  • npm run prepare

    运行命令,会自动在项目根目录创建

    .husky

    文件夹
  • 然后运行

    npx husky add .husky/pre-commit "npm run lint"

    ,会自动在

    .husky

    目录添加

    pre-commit

    文件,并添加了相应的git hooks文件,

    pre-commit

    文件里也自动写入了

    npm run lint

    内容,具体内容可自定义。
  • 上一步加了

    npm run lint

    的内容,意思就是git commit的时候自动执行npm run lint命令来校验,所以需要在

    package.json

    的scripts里添加命令,lint命令内容根据需要自行修改:
  • 大功告成。另外,关于团队合作方面,其实在执行

    npm i

    的时候会自动执行

    npm run prepare

    命令,并根据.husky目录的钩子文件自动生成相关的其他文件,所以,只要不删prepare命令,不忽略.husky文件夹,团队配置一致性就没有问题。

lint-staged

v12 版本的配置同样也跟着

husky

变了,具体参考官方文档。

一、概述

这里的统一代码风格包括编辑器基本配置、代码校验、格式化工具、git提交前校验等,强烈建议配置下,特别是eslint起初可能不习惯,其实三五天时间就适应了,能帮助避免很多低级错误,另外对于团队开发也很重要。

先介绍下这里需要用到的几个工具:

  • editorconfig

    统一编辑器基本配置
  • eslint

    js校验工具。
  • stylelint

    css校验工具,也支持less等css预处理器。
  • prettier

    代码格式化工具,主要用于格式化html部分的代码,一般写代码习惯好就不需要这个,可配置项很少,有点鸡肋吧,但有总比没有强,虽然我配置后从来没用到过。。。
  • husky

    是一个gitHook工具,可以配置git的一些钩子,本文主要用来配置 commit 钩子。
  • lint-staged

    是一个在git暂存文件上运行lint校验的工具,配合husky配置commit钩子,用于git commit前的强制校验。

二、editorConfig

因为前端开发有些人用vscode,也有一部分人用webstorm,有些人用tab缩进,有些人用俩空格缩进,有些人用四个空格缩进,等等这些,这个工具就是用于统一不同人编辑器的项目配置。

  • 对于vscode,需要安装扩展:

    EditorConfig for VS Code

  • 然后项目根目录添加文件

    .editorconfig

    ,编写以下配置:
# https://editorconfig.org
root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = crlf
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
insert_final_newline = false
trim_trailing_whitespace = false
           

三、eslint

js校验必备,注意eslint只针对js或ts做校验,按以下方式配置完后可做到保存时自动校验并修复,但是建议写代码时还是按照规范来写,不要太依赖它的自动修复功能。

1、配置vscode

  • 安装vscode扩展

    eslint

  • 设置文件

    settings.json

    里添加配置
"eslint.validate": [
  "html",
  "vue",
  "vue-html",
  "javascript",
  "javascriptreact", 
  "typescript",
  "typescriptreact"
],
"editor.codeActionsOnSave": {
  "source.fixAll.eslint": true,
  "source.fixAll.stylelint": true
},
           

2、对于通用js项目

推荐使用standard配置规范。

(1)项目安装依赖

npm i -D eslint eslint-config-standard eslint-plugin-standard eslint-plugin-promise eslint-plugin-import eslint-plugin-node
           

(2)添加项目配置文件

  • 项目根目录添加eslint配置文件

    .eslintrc.js

module.exports = {
  env: {
    commonjs: true,
    es6: true,
    node: true
  },
  extends: [
    'standard',
    'eslint:recommended',
  ],
  globals: {
  },
  parserOptions: {
    ecmaVersion: 11
  },
  rules: {
    'no-console': 'off',
    'no-debugger': 'off',
  }
}
           
  • 项目根目录添加eslint忽略配置文件

    .eslintignore

.DS_Store
node_modules
dist
build
public
.eslintrc.js
           

(3)可选

(非必需项,可能会影响webpack编译速度,谨慎使用)

对于webpack项目,

eslint-webpack-plugin

可以帮助在webpack编译或热更新时实时校验代码并作出错误提示,替代以前的eslint-loader。

  • 安装依赖:
npm i eslint-webpack-plugin -D
           
  • 在webpack的plugins配置文件(例如

    webpack.base.conf.js

    )里添加:
const ESLintPlugin = require('eslint-webpack-plugin');

module.exports = {
  // ...
  plugins: [
  	...
  	new ESLintPlugin({
		extensions: [
			'vue', 'html', 'js', 'ts', 'jsx', 'tsx'
		]
	})
  ],
  // ...
}
           

3、对于vue-cli脚手架项目

推荐使用官方脚手架默认的eslint校验配置,如果在一开始用脚手架生成项目时未选择eslint,可以通过以下方式手动添加:

(1)项目安装依赖包

npm i -D @vue/cli-plugin-eslint @vue/eslint-config-standard babel-eslint eslint eslint-plugin-vue
           

(2)添加项目配置文件

  • 项目根目录添加eslint配置文件

    .eslintrc.js

module.exports = {
  root: true,
  env: {
    node: true
  },
  extends: [
    'plugin:vue/essential',
    '@vue/standard'
  ],
  parserOptions: {
    parser: 'babel-eslint'
  },
  globals: {},
  rules: {
    'no-console': 'off',
    'no-debugger': 'off'
  },
}
           
  • 项目根目录添加eslint忽略配置文件

    .eslintignore

public
dist
           

4、对于create-react-app脚手架项目

推荐使用 eslint-config-standard + eslint-plugin-react

(1)项目安装依赖包

npm i -D eslint eslint-config-standard eslint-plugin-standard eslint-plugin-promise eslint-plugin-import eslint-plugin-node eslint-plugin-react
           

(2)添加项目配置文件

  • 项目根目录添加eslint配置文件

    .eslintrc.js

module.exports = {
  env: {
    browser: true,
    es2020: true,
    node: true
  },
  extends: [
    'standard',
    'eslint:recommended',
    'plugin:react/recommended'
  ],
  parser: 'babel-eslint',
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 11,
    sourceType: 'module'
  },
  plugins: [],
  settings: {
    react: {
      version: 'detect'
    }
  },
  rules: {
    'no-console': 'off',
    'no-debugger': 'off',
    'space-before-function-paren': 'off',
    'camelcase': 'off',
    'comma-dangle': 'off',
    'react/prop-types': 'off',
    'react/display-name': 'off'
  }
}
           
  • 项目根目录添加eslint忽略配置文件

    .eslintignore

scripts
config
public
build
.eslintrc.js
           

四、stylelint

stylelint只针对css或css预处理器的代码做校验。(注意:配置了vscode后会对所有项目所有文件的样式代码都生效,不管你项目里有没有相关配置文件,谨慎使用)。

1、配置vscode

  • 安装vscode扩展

    stylelint

  • 设置文件

    settings.json

    里添加配置
"editor.codeActionsOnSave": {
  "source.fixAll.eslint": true,
  "source.fixAll.stylelint": true
},
"css.validate": false,
"less.validate": false,
"scss.validate": false,
           
  • 如需要自定义编辑器默认配置,通过

    settings.json

    里配置

    stylelint.configOverrides

    的rules实现:
// 这里的配置优先级低于.stylelintrc.js文件,适合用作编辑器的默认配置
"stylelint.configOverrides": {
  "rules": {
    // 示例,配置支持小程序rpx单位
    "unit-no-unknown": [true,
      { "ignoreUnits": ["rpx"] }
    ],
  },
  // 示例,配置忽略列表文件
  "ignoreFiles": [
	  "node_modules/**/*",
	  "dist/**/*",
	  "**/*.js",
	  "**/*.jsx",
	  "**/*.tsx",
	  "**/*.ts"
	]
},
           

2、安装依赖包

npm i stylelint stylelint-config-standard -D
           

3、添加项目配置文件

  • 项目根目录添加 .stylelintrc.js
module.exports = {
  extends: ['stylelint-config-standard'],
  rules: {
    'rule-empty-line-before': null,
    'font-family-no-missing-generic-family-keyword': null,
    'no-descending-specificity': null,
    'color-hex-case': null,
    'no-empty-source': null,
    'block-no-empty': null,
    "selector-pseudo-class-no-unknown": [true,
      { "ignorePseudoClasses": ["global"] }
    ]
  },
  ignoreFiles: [
    'node_modules/**/*',
    'public/**/*',
    'dist/**/*',
    '**/*.js',
    '**/*.jsx',
    '**/*.tsx',
    '**/*.ts'
  ],
}
           

ps:关于

stylelint-webpack-plugin

插件,功能类似于eslint的

eslint-webpack-plugin

,经实测会影响webpack热更新速度,不建议使用。

五、prettier

prettier是一套代码格式规范,一般用作格式化工具,但是配置项太少,和eslint的格式效果也可能会有冲突,所以不建议开启编辑器的保存自动格式化功能,js交给eslint,css交给stylelint,这个主要就用于html部分的格式化。

对个人编码习惯不好的懒癌童鞋有奇效,对于习惯良好的还是按照自己的习惯就好,不过还是建议试用一下它的格式化效果和自己的代码对比下,取长补短,形成自己的最佳实践。

1、添加项目配置文件

  • 项目根目录添加

    .prettierrc.js

module.exports = {
  'eslintIntegration': true,
  'stylelintIntegration': true,
  'tabWidth': 2,
  'singleQuote': true,
  'semi': false
}
           

2、配置vscode

  • vscode添加扩展:

    Prettier

  • 设置文件

    settings.json

    里添加配置
"[html]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[css]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[less]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[scss]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascript]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[vue]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescript]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascriptreact]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescriptreact]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
},

"prettier.singleQuote": true,
"prettier.semi": false,

"vetur.format.defaultFormatter.html": "prettier",
"vetur.format.defaultFormatterOptions": {
  "prettier": {
    "eslintIntegration": true,
	"stylelintIntegration": true
  }
},
           

六、husky + lint-staged

只是单纯引入校验如果不强制要求就等于没做,总会有人偷懒,所以还是要约束一下。

  • husky

    用于git执行钩子前做校验,
  • lint-staged

    用于只校验git暂存区的文件。
  • 这里要实现的功能是在

    git commit

    命令运行时先校验lint(包括eslint和stylelint)是否通过,未通过则不予commit。

1、安装依赖包

npm i [email protected] [email protected] -D
           

2、配置package.json

  • scripts里添加命令eslint 和 stylelint:
"scripts": {
   "eslint": "eslint--config .eslintrc.js **/*.{vue,html,js,ts,jsx,tsx} --fix",
   "stylelint": "stylelint --config .stylelintrc.js **/*.{vue,html,css,less,scss,sass} --fix"
 }
           
  • 添加 lint-staged 相关配置:
"husky": {
   "hooks": {
     "pre-commit": "lint-staged"
   }
},
"lint-staged": {
   "*.{vue,html,js,ts,jsx,tsx}": [
     "npm run eslint"
   ],
   "*.{vue,html,css,less,scss,sass}": [
     "npm run stylelint"
   ]
},
           

这里的配置对vue和react以及ts文件拓展名都做了通用的判断处理,实际项目中可以移除用不到的拓展名;

需要注意,强制校验相关的控制文件都是在.git文件夹内,如果不小心删除了这个文件夹,需要重新安装依赖包(husky)后强制校验才能生效。

七、typeScript 校验

如果项目使用ts代码,需要额外配置ts相关的校验。

1、配置指引

首先需要按上述的eslint配置教程配置好eslint,然后再往下看。

(1)vue-cli项目

仍然是推荐使用官方脚手架默认的ts校验配置,如果在用脚手架生成项目时未选择ts,可按以下方式配置:

  • 安装依赖:
npm i D typescript @vue/cli-plugin-typescript @vue/eslint-config-typescript @typescript-eslint/[email protected] @typescript-eslint/[email protected] 
           
  • 修改

    .eslintrc.js

module.exports = {
  root: true,
  env: {
    node: true
  },
  extends: [
    'plugin:vue/essential',
    '@vue/standard',
    '@vue/typescript/recommended' // 修改点一
  ],
  parserOptions: {
    ecmaVersion: 2020 // 修改点二
  },
  globals: {},
  rules: {
    'no-console': 'off',
    'no-debugger': 'off'
  }
}
           

(2)create-react-app项目

  • 插件

    typescript-eslint

    用作ts校验,是eslint的一个扩展插件,引入后修改

    .eslintrc.js

    配置即可,具体使用配置参考插件官方教程,步骤已经非常详细,这里就不多说了,也可以参考文末的附录作对比;
  • 插件tslint已经停止维护,不建议使用;
  • 如果遇到类似的ts校验报错信息:‘React’ was used before it was defined

    需要在

    .eslintrc.js

    里添加以下rules规则:
"no-use-before-define": "off",
"@typescript-eslint/no-use-before-define": ["error"],
           

2、其他注意点

  • lint-staged相关配置里需要添加.ts后缀文件的支持,如果是react项目还要添加.jsx和.tsx文件支持。
  • vscode下有时会有莫名其妙ts不生效的问题,尝试解决方法:把项目文件夹拖到vscode以工作区的形式显示,并将该项目拖到最顶部使其在工作区排在第一位,然后重启vscode。

3、附录

(1)eslintrc.js

附上react+ts项目的

.eslintrc.js

配置供参考:

module.exports = {
  env: {
    browser: true,
    es2020: true,
    node: true
  },
  extends: [
    'standard',
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:@typescript-eslint/recommended'
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 11,
    sourceType: 'module'
  },
  plugins: [],
  settings: {
    react: {
      version: 'detect'
    }
  },
  rules: {
    'no-console': 'off',
    'no-debugger': 'off',
    'space-before-function-paren': 'off',
    'camelcase': 'off',
    'comma-dangle': 'off',
    'react/prop-types': 'off',
    'react/display-name': 'off',
    '@typescript-eslint/member-delimiter-style': 0,
    '@typescript-eslint/no-explicit-any': 0,
    '@typescript-eslint/triple-slash-reference': 0,
    '@typescript-eslint/explicit-module-boundary-types': 0,
    "no-use-before-define": "off",
	"@typescript-eslint/no-use-before-define": ["error"],
  }
}
           

(2)相关依赖版本:

"@typescript-eslint/eslint-plugin": "^4.0.1",
"@typescript-eslint/parser": "^4.0.1",
"eslint": "^7.9.0",
"eslint-config-standard": "^14.1.1",
"eslint-loader": "^4.0.2",
"eslint-plugin-import": "^2.22.0",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-react": "^7.21.1",
"eslint-plugin-standard": "^4.0.1",
           

继续阅读