1. 項目中集成eslint
全局安裝eslint,同時作為項目依賴安裝。
cnpm i eslint -g cnpm i eslint -D
生成eslint配置文件
eslint --init
生成 .eslintrc.js (選擇react Airbnb擴展)
module.exports = { env: { browser: true, // 瀏覽器環境中的全局變量。 es6: true, // 啟用除了 modules 以外的所有 ECMAScript 6 特性(該選項會自動設置 ecmaVersion 解析器選項為 6)。 node: true, // Node.js 全局變量和 Node.js 作用域。 }, // extends 屬性值可以省略包名的前綴 eslint-config-airbnb。 extends: [ 'plugin:react/recommended', 'airbnb', ], globals: { Atomics: 'readonly', SharedArrayBuffer: 'readonly', },
// 解析器選項 parserOptions: { ecmaFeatures: { jsx: true, // 啟用 JSX 支持 JSX 語法並不等同於支持 React,同時啟用 plugins設置 }, ecmaVersion: 2018, // 默認設置為 3,5(默認), 你可以使用 6、7、8、9 或 10 來指定你想要使用的 ECMAScript 版本。你也可以用使用年份命名的版本號指定為 2015(同 6),2016(同 7),或 2017(同 8)或 2018(同 9)或 2019 (same as 10) sourceType: 'module', // 設置為 "script" (默認) 或 "module"(如果你的代碼是 ECMAScript 模塊)。 }, // 使用第三方插件 插件名稱可以省略 eslint-plugin- 前綴。這里為eslint-plugin-react plugins: [ 'react', ], rules: { }, };
注意:支持 ES6 語法並不意味着同時支持新的 ES6 全局變量或類型(比如 Set
等新類型)。對於 ES6 語法,使用 { "parserOptions": { "ecmaVersion": 6 } }
;對於新的 ES6 全局變量,使用 { "env":{ "es6": true } }。
{ "env": { "es6": true } }
自動啟用es6語法,但 { "parserOptions": { "ecmaVersion": 6 } }
不自動啟用es6全局變量。
2. 集成到webpack中
需要安裝babel-eslint(eslint支持babel), eslint-loader(eslint支持webpack)
cnpm i eslint babel-eslint eslint-loader -D
配置eslintrc.js
{ "parser": "babel-eslint", }
webpack.config.js
module: { rules: [
{ test: /\.(js|jsx)$/, exclude: /node_modules/, use: ['babel-loader', { loader: 'eslint-loader', //先eslint 后babel options: { fix: true, // 自動修復eslint cache: true // 緩存 }, }]
}, ...
3. 在代碼commit前進行eslint校驗
安裝pre-commit
cnpm i pre-commit -D
package.json
{ "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "lint": "eslint .", // 校驗所有文件 "fix": "eslint --fix ." // 修復所有文件 }, "pre-commit": [ "fix", "lint" // 依次執行 npm run fix、 npm run lint 命令 ], }
4. 在vscode中保存修復eslint和快捷鍵設置
安裝eslint擴展
設置與鍵盤快捷方式設置
eslint設置
快捷鍵綁定
結合editorconfig自動格式化
.editorconfig 如下
root = true # 根目錄的配置文件,編輯器會由當前目錄向上查找,如果找到 `roor = true` 的文件,則不再查找 [*] # 匹配所有的文件 indent_style = space # 空格縮進 indent_size = 4 # 縮進空格為4個 max_line_length = 100 # 單行最大長度 end_of_line = lf # 文件換行符是 linux 的 `\n` charset = utf-8 # 文件編碼是 utf-8 trim_trailing_whitespace = true # 不保留行末的空格 insert_final_newline = true # 文件末尾添加一個空行 curly_bracket_next_line = false # 大括號不另起一行 spaces_around_operators = true # 運算符兩遍都有空格 indent_brace_style = 1tbs # 條件語句格式是 1tbs [*.{js,jsx}] # 對所有的 js 文件生效 quote_type = single # 字符串使用單引號 [*.{html,less,css,json}] # 對所有 html, less, css, json 文件生效 quote_type = double # 字符串使用雙引號 [package.json] # 對 package.json 生效 indent_size = 2 # 使用2個空格縮進
以上。