使用React JS, ESLint, Prettier和git precommit hooks管理前端代碼

在前端項目開發中, 開發style因人而異, 爲了讓team的code面對所有開發人員可維護, 可讀, 最好的方法是使用linter. Linter 可以統一team代碼規範, 檢測潛在的bugs, 性能問題等. precommit是git的一個鉤子, 它能讓你在提交代碼之前乾點事, 今天就demo一下如何在一個項目裏使用這些tools.編輯工具統一爲vscode.

1, 什麼是linter?

    說白了就是一個幫你分析程序代碼, 檢測程序中潛在的輸入錯誤工具. 它能幫開發快速的定位錯誤, 提示如何改正等. 現在js社區最流行的linter是Prettier和Eslint. 

2,創建項目

    找個空曠的目錄, 執行:

 

npx create-react-app eslint-app 
cd eslint-app 
npm start

3,安裝eslint

 

 

npm install eslint --save-dev

# or

yarn add eslint --dev

初始化eslint

 

 

npx eslint --init

 

按照上面的選擇會生成一個.eslintrc.json在項目根目錄,內容如下

 

{

     "env": {

         "browser":  true,

         "es6":  true

    },

     "extends": [

         "plugin:react/recommended",

         "airbnb"

    ],

     "globals": {

         "Atomics":  "readonly",

         "SharedArrayBuffer":  "readonly"

    },

     "parserOptions": {

         "ecmaFeatures": {

             "jsx":  true

        },

         "ecmaVersion":  11,

         "sourceType":  "module"

    },

     "plugins": [

         "react"

    ],

     "rules": {

    }

}

如果想覆蓋  Airbnb規則在在rules裏面添加rule就行. 傳送Eslint Rules

4, 安裝Prettier

作爲vscode的一般插件安裝就好了. 

安裝好之後在terminal執行命令把這幾個包裝上

npm i prettier eslint-config-prettier eslint-plugin-prettier -D

然後更新.eslintrc文件的extends如下:

"extends": [ "airbnb", "plugin:prettier/recommended" ]

如果不想用Prettier的配置, 可以在根目錄新建一個名爲.prettierrc的文件, 配置自己的配置.

 

{

   "root":  true,

   "printWidth":  120,

   "trailingComma":  "none",

   "bracketSpacing":  true,

   "jsxBracketSameLine":  true,

   "endOfLine":  "lf",

   "singleQuote":  false,

   "jsxSingleQuote":  false,

   "semi":  true,

   "parser":  "typescript"

}

 

5, 讓vscode每次format code當保存文件的時候

 

打開vscode的setting配置  添加如下配置

 

{

     "workbench.iconTheme":  "vscode-icons",

     "editor.fontSize":  16,

     "editor.formatOnPaste":  false,

     "[javascript]": {},

     "files.associations": {

         "*.js":  "javascriptreact",

         "*.wxss":  "css",

         "*.wxml":  "html"

    },

     "eslint.lintTask.enable":  true,

     "eslint.validate": [

         "javascript",

         "javascriptreact",

         "typescript",

         "typescriptreact",

    ],

     "javascript.updateImportsOnFileMove.enabled":  "always",

     "search.exclude": {

         "**/node_modules":  false

    },

     "editor.codeActionsOnSave": {

         "source.fixAll.eslint":  true

    },

     "editor.formatOnSave":  true,

     "typescript.updateImportsOnFileMove.enabled":  "always",

     "window.zoomLevel":  0

}

這樣基本的配置就算完成了, 可以檢查代碼的格式, 一般性的代碼錯誤了

 

6, 設置Husky pre-commit hook 

這一步看似是沒什麼必要, 因爲每次format的時候已經改了, 可能有些人懶得改設置了disable, 就當再上個保險吧.

(1), 什麼是Husky?

Husky讓我們在git commit和push之前能運行一些命令.

(2), 什麼是lint-staged?

lint-staged 能讓我們在git staged狀態的文件上跑多個linter, 在這跑的就是Eslint和Prettier.

下面就說說怎麼用husky

先安裝幾個必要的包

 

使用 npm
npm install --save-dev husky lint-staged eslint eslint-config-airbnb prettier

使用 yarn
yarn add --dev husky lint-staged eslint eslint-config-airbnb prettier

 

打開package.json, 和dependencies同級添加如下配置:

 

"husky": {

     "hooks": {

       "pre-commit":  "lint-staged"

    }

  },

   "lint-staged": {

     "./src/*.{js,jsx,ts,tsx}": [

       "npm run lint:js",

       "npx prettier --write",

       "eslint src/*.js --fix-dry-run",

       "git add"

    ],

     "**/*.less": [

       "stylelint --syntax less",

       "npm run prettier",

       "git add"

    ]

  },

上面的code會對所有的js,jsx,ts,tsx文件跑一遍Prettier and ESLint rules, 當然這個正則可以修改爲自己想匹配了跑的.

添加了上面配置, 如果有eslint報錯就沒法成功提交, 這樣我們統一代碼規範的目的就達到了.

最後貼上我的配置:

VsCode:

 

{

     "workbench.iconTheme":  "vscode-icons",

     "editor.fontSize":  16,

     "editor.formatOnPaste":  false,

     "[javascript]": {},

     "files.associations": {

         "*.js":  "javascriptreact",

         "*.wxss":  "css",

         "*.wxml":  "html"

    },

     "eslint.lintTask.enable":  true,

     "eslint.validate": [

         "javascript",

         "javascriptreact",

         "typescript",

         "typescriptreact",

    ],

     "javascript.updateImportsOnFileMove.enabled":  "always",

     "search.exclude": {

         "**/node_modules":  false

    },

     "editor.codeActionsOnSave": {

         "source.fixAll.eslint":  true

    },

     "editor.formatOnSave":  true,

     "typescript.updateImportsOnFileMove.enabled":  "always",

     "window.zoomLevel":  0

}

 

Eslint:

 

 

{

   "env": {

     "browser":  true,

     "es6":  true

  },

   "extends": [ "plugin:prettier/recommended",  "airbnb"],

   "globals": {

     "Atomics":  "readonly",

     "SharedArrayBuffer":  "readonly"

  },

   "parserOptions": {

     "ecmaFeatures": {

       "jsx":  true

    },

     "ecmaVersion":  11,

     "sourceType":  "module"

  },

   "plugins": [ "react"],

   "rules": {

     "react/jsx-filename-extension": [

       1,

      {

         "extensions": [ ".js",  ".jsx"]

      }

    ],

     /**

    "always" enforces braces around the function body

    "as-needed" enforces no braces where they can be omitted (default)

    "never" enforces no braces around the function body (constrains arrow functions to the role of returning an expression)

    */

     "arrow-body-style": [ "error",  "as-needed"],

     /**

    "properties": "always" (default) enforces camelcase style for property names

    "properties": "never" does not check property names

    "ignoreDestructuring": false (default) enforces camelcase style for destructured identifiers

    "ignoreDestructuring": true does not check destructured identifiers (but still checks any use of those identifiers later in the code)

    "ignoreImports": false (default) enforces camelcase style for ES2015 imports

    "ignoreImports": true does not check ES2015 imports (but still checks any use of the imports later in the code except function arguments)

    allow (string[]) list of properties to accept. Accept regex.

    */

     "camelcase": [ "error",  "never"],

     "no-param-reassign":[ "error", {  "props":  false }],

     // "allowForLoopAfterthoughts": true allows unary operators ++ and -- in the afterthought (final expression) of a for loop.

     "allowForLoopAfterthoughts":[ "error", {  "allowForLoopAfterthoughts":  true }],

     "prefer-template":[ "error"],

     "no-use-before-define": [ "error", {  "functions":  true,  "classes":  true }]

  }

}

 

Prettier:

 

 

{

   "root":  true,

   "printWidth":  120,

   "trailingComma":  "all",

   "bracketSpacing":  true,

   "jsxBracketSameLine":  true,

   "jsxBrackets": true,

   "endOfLine":  "lf",

   "singleQuote":  true,

   "jsxSingleQuote":  false,

   "semi":  true,

   "parser":  "typescript"

}

 

 

-- end --

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章