項目中代碼風格或者代碼規範的遵守,在自覺的情況下就是強制要求。從git提交驗證開始做起。
首選安裝
npm install --save-dev eslint babel-eslint pre-commit
npm install --save-dev lint-staged eslint-config-standard eslint-plugin-node
npm install --save-dev eslint-plugin-promise eslint-plugin-standard
eslint配置文件初始化
node_modules/.bin/eslint --init
選擇步驟如下
一、
二、
三、
四、
五、
六、
七、
八、生成如下文件
ps: .eslintignore 需要忽略的校驗文件,比如
/src/sdk/libs
/src/page/groupChatRoom
/src/imports
修改.eslintrc.js符合項目需求
module.exports = {
env: {
browser: true,
es6: true,
node: true,
},
extends: ['plugin:react/recommended', 'standard'],
parser: 'babel-eslint',
plugins: ['react', 'taro'],
globals: {
Atomics: 'readonly',
SharedArrayBuffer: 'readonly',
},
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 2018,
sourceType: 'module',
},
rules: {
'no-unused-vars': 2,
'no-tabs': 'off',
indent: [
2,
'tab',
{
SwitchCase: 1,
},
],
'no-mixed-spaces-and-tabs': [0, false],
'no-inner-declarations': [2, 'functions'],
'no-trailing-spaces': 2,
'default-case': 2,
'no-redeclare': 2,
'no-extra-semi': 2,
'handle-callback-err': 0,
'semi-spacing': [
2,
{
before: false,
after: true,
},
],
'consistent-this': [1, '_that'],
'jsx-quotes': [2, 'prefer-double'],
'no-eval': 1,
'no-func-assign': 2,
'no-fallthrough': 2,
'no-var': 2,
'no-with': 2,
'strict': 2,
'no-undef': 0,
'no-console': 0,
'no-unreachable': 0,
'no-spaced-func': 2,
'constructor-super': 2,
'no-dupe-class-members': 2,
'no-duplicate-case': 2,
'no-self-compare': 2,
'comma-spacing': [
2,
{
before: false,
after: true,
},
],
'new-parens': 2,
'no-array-constructor': 2,
'no-class-assign': 2,
'no-cond-assign': 2,
'new-cap': [
2,
{
newIsCap: true,
capIsNew: false,
},
],
'no-multiple-empty-lines': [
2,
{
max: 2,
},
],
'guard-for-in': 2,
'arrow-spacing': [2, { before: true, after: true }],
'block-scoped-var': 2,
'key-spacing': [2, { mode: 'strict' }],
'func-call-spacing': ['error', 'never'],
'no-new': 2,
'require-await': 2,
'no-new-object': 2,
'no-extra-parens': 1,
'comma-dangle': 0,
'react/display-name': 0,
'react/prefer-es6-class': 2,
'react/no-deprecated': 0,
'react/jsx-uses-react': 1,
'react/jsx-uses-vars': 2,
'react/jsx-filename-extension': [
1,
{
extensions: ['.js', '.jsx', '.tsx'],
},
],
'react/react-in-jsx-scope': 0,
'react/jsx-indent-props': ['error', 'tab'],
'react/jsx-tag-spacing': 0,
},
};
package.json配置
####### 添加npm命令
"lint": "eslint src/**/*.js",
執行npm run lint 如下結果
####### git提交驗證配置
{
"pre-commit": [
"lint-staged"
],
"lint-staged": {
"src/**/*.{js,jsx}": [
"npm run lint-staged:es",
"eslint --fix",
"git add"
]
},
"scripts": {
"lint-staged:es": "eslint --ext src/**/*.{js,jsx}",
"lint-staged": "lint-staged",
"lint": "eslint src/**/*.js"
}
}
當git 提交時,驗證不通過出現如下提示