vue項目中使用eslint+prettier規范與檢查代碼的方法


1.前言

  在團隊協作中,為避免低級 Bug、以及團隊協作時不同代碼風格對彼此造成的困擾與影響,會預先制定編碼規范。使用 Lint 工具和代碼風格檢測工具,則可以輔助編碼規范執行,有效控制代碼質量。EsLint 則是其中一個很好的工具。

EsLint 提供以下支持:

  • ES6
  • AngularJS
  • JSX
  • Style 檢查
  • 自定義錯誤和提示

EsLint 提供以下幾種校驗:

  • 語法錯誤校驗
  • 不重要或丟失的標點符號,如分號
  • 未被使用的參數提醒
  • 漏掉的結束符,如}
  • 確保樣式的統一規則,如 sass 或者 less
  • 檢查變量的命名
  • 影響性能的代碼提醒,如 v-if 和 v-for 同時使用

2.eslint 配置

2.1 代碼規范

  本項目基本規范是依托於 vue 官方的 eslint-plugin-vue。並使用 Prettier 格式化代碼,使樣式與規則保持一致。

.eslintrc.js 配置如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
{
root: true , // 當前配置為根配置,將不再從上級文件夾查找配置
parserOptions: {
  parser: 'babel-eslint' , // 采用 babel-eslint 作為語法解析器
  sourceType: 'module' // 指定來源的類型,有兩種script或module
  ecmaVersion: 6, //指定ECMAScript支持的版本,6為ES6
},
env: {
  browser: true , // 設置為所需檢查的代碼是在瀏覽器環境運行的
  es6: true // 設置所需檢查代碼為 es6 語法書寫
},
extends: [ 'plugin:vue/recommended' , 'eslint:recommended' ], // 擴展使用 vue 檢查規則和eslint推薦規則
  rules: {
   'vue/attribute-hyphenation' : 0, // 忽略屬性連字
   'vue/max-attributes-per-line' :[2, { singleline: 10, multiline: { max: 1, allowFirstLine: false } }], // 每行最大屬性
   'vue/singleline-html-element-content-newline' : 'off' , // 單行html元素內容在新的一行
   'vue/multiline-html-element-content-newline' : 'off' , // 多行html元素內容在新的一行
   'vue/html-closing-bracket-newline' : 'off' , // html右括號在新的一行
   'vue/no-v-html' : 'off' , // 不使用v-html
   'vue/html-self-closing' : 0, // 忽略html標簽自閉合
   'accessor-pairs' : 2, // 應同時設置setter和getter
   'arrow-spacing' : [2, { before: true , after: true }], // 箭頭間距
   'vue/require-default-prop' : 0, // 不檢查默認屬性
   'vue/require-prop-types' : 0, // 不檢查默認類型
   'block-spacing' : [2, 'always' ], // 塊間距
   'brace-style' : [2, '1tbs' , { allowSingleLine: true }], // 大括號樣式允許單行
   'camelcase' : [2, { properties: 'always' }], //為屬性強制執行駝峰命名
   'comma-dangle' : [2, 'never' ], // 逗號不使用懸掛
   'comma-spacing' : [2, { before: false , after: true }], // 逗號間距
   'comma-style' : [2, 'last' ], //(默認)與數組元素,對象屬性或變量聲明在同一行之后和同一行需要逗號
   'constructor-super' : 2,
   'consistent-this' : [2, 'that' ], //強制this別名為that
   'curly' : [2, 'multi-line' ], // 當一個塊只包含一條語句時,不允許省略花括號。
   'dot-location' : [2, 'property' ], //成員表達式中的點應與屬性部分位於同一行
   'eol-last' : 2, // 強制文件以換行符結束(LF)
   'eqeqeq' : [ 'error' , 'always' , { null : 'ignore' }], // 強制使用全等
   'generator-star-spacing' : [2, { before: true , after: true }], // 生成器中'*'兩側都要有間距
   'global-require' : 1, // 所有調用require()都位於模塊的頂層
   'indent' : [2, 2, { SwitchCase: 2 }], //縮進風格
   'key-spacing' : [2, { beforeColon: false , afterColon: true }], // 強制在對象字面量屬性中的鍵和值之間保持一致的間距
   'keyword-spacing' : [2, { before: true , after: true }], // 關鍵字如if/function等的間距
   'new-cap' : [2, { newIsCap: true , capIsNew: false }], // 允許在沒有new操作符的情況下調用大寫啟動的函數;(默認)要求new使用大寫啟動函數調用所有操作符
   'new-parens' : 2, // JavaScript通過new關鍵字調用函數時允許省略括號
   'no-array-constructor' : 1, // 不允許使用Array構造函數。除非要指定生成數組的長度
   'no-console' : process.env.NODE_ENV === 'production' ? 'error' : 'off' , // 只有開發環境可以使用console
   'no-class-assign' : 2, // 不允許修改類聲明的變量
   'no-const-assign' : 2, // 不能修改使用const關鍵字聲明的變量
   'no-control-regex' : 0, // 不允許正則表達式中的控制字符
   'no-debugger' : process.env.NODE_ENV === 'production' ? 'error' : 'off' , // 只有開發環境可以使用debugger
   'no-delete-var' : 2, // 不允許在變量上使用delete操作符
   'no-dupe-args' : 2, // 不允許在函數聲明或表達式中使用重復的參數名稱
   'no-dupe-class-members' : 2, // 不允許在類成員中使用重復的參數名稱
   'no-dupe-keys' : 2, // 不允許在對象文字中使用重復鍵
   'no-duplicate-case' : 2, // 不允許在switch語句的case子句中使用重復的測試表達式
   'no-empty-character-class' : 2, // 不允許在正則表達式中使用空字符類
   'no-empty-pattern' : 2, // 不允許空塊語句
   'no-eval' : 2, // 不允許使用eval
   'no-ex-assign' : 2, // 不允許在catch子句中重新分配例外
   'no-extend-native' : 2, // 不允許直接修改內建對象的原型
   'no-extra-boolean-cast' : 2, // 禁止不必要的布爾轉換
   'no-extra-parens' : [2, 'functions' ], // 僅在函數表達式附近禁止不必要的括號
   'no-fallthrough' : 2, //消除一個案件無意中掉到另一個案件
   'no-floating-decimal' : 2, //消除浮點小數點,並在數值有小數點但在其之前或之后缺少數字時發出警告
   'no-func-assign' : 2, // 允許重新分配function聲明
   'no-implied-eval' : 2, // 消除隱含eval()
   'no-inner-declarations' : [2, 'functions' ], // 不允許function嵌套塊中的聲明
   'no-invalid-regexp' : 2, //不允許RegExp構造函數中的無效正則表達式字符串
   'no-irregular-whitespace' : 2, //捕獲無效的空格
   'no-iterator' : 2, //消除陰影變量聲明
   'no-label-var' : 2, //禁止創建與范圍內的變量共享名稱的標簽
   'no-labels' : [2, { allowLoop: false , allowSwitch: false }], // 消除 JavaScript 中使用帶標簽的語句
   'no-lone-blocks' : 2, //消除腳本頂層或其他塊中不必要的和可能混淆的塊
   'no-mixed-spaces-and-tabs' : 2, // 不允許使用混合空格和制表符進行縮進
   'no-multi-spaces' : 2, // 禁止在邏輯表達式,條件表達式,聲明,數組元素,對象屬性,序列和函數參數周圍使用多個空格
   'no-multi-str' : 2, // 防止使用多行字符串
   'no-multiple-empty-lines' : [2, { max: 1 }], // 最多一個空行
   'no-native-reassign' : 2, // 不允許修改只讀全局變量
   'no-new-object' : 2, // 不允許使用Object構造函數
   'no-new-require' : 2, // 消除new require表達的使用
   'no-new-symbol' : 2, // 防止Symbol與new 同時使用的意外錯誤
   'no-new-wrappers' : 2, // 杜絕使用String,Number以及Boolean與new操作
   'no-obj-calls' : 2, // 不允許調用Math,JSON和Reflect對象作為功能
   'no-octal' : 2, // 不允許使用八進制文字
   'no-octal-escape' : 2, // 不允許字符串文字中的八進制轉義序列
   'no-path-concat' : 2, // 防止 Node.js 中的目錄路徑字符串連接無效
   'no-redeclare' : 2, // 消除在同一范圍內具有多個聲明的變量
   'no-regex-spaces' : 2, // 在正則表達式文字中不允許有多個空格
   'no-return-assign' : [2, 'except-parens' ], // 消除return陳述中的任務,除非用括號括起來
   'no-self-assign' : 2, // 消除自我分配
   'no-self-compare' : 2, // 禁止比較變量與自身
   'no-sequences' : 2, // 禁止使用逗號運算符
   'no-sparse-arrays' : 2, // 不允許稀疏數組文字
   'no-this-before-super' : 2, // 在呼call前標記this/super關鍵字super()
   'no-throw-literal' : 2, // 不允許拋出不可能是Error對象的文字和其他表達式
   'no-trailing-spaces' : 2, // 不允許在行尾添加尾隨空白
   'no-undef' : 2, // 任何對未聲明的變量的引用都會導致錯誤
   'no-undef-init' : 2, // 消除初始化為undefined的變量聲明
   'no-underscore-dangle' : 2, // 標識符不能以_開頭或結尾
   'no-unexpected-multiline' : 2, // 不允許混淆多行表達式
   'no-unmodified-loop-condition' : 2, // 查找循環條件內的引用,然后檢查這些引用的變量是否在循環中被修改
   'no-unneeded-ternary' : [2, { defaultAssignment: false }], // 不允許將條件表達式作為默認的分配模式
   'no-unreachable' : 2, // 不允許可達代碼return,throw,continue,和break語句后面還有語句。
   'no-unsafe-finally' : 2, // 不允許return,throw,break,和continue里面的語句finally塊
   'no-unused-vars' : [2, { vars: 'all' , args: 'after-used' }],
   // 消除未使用的變量,函數和函數的參數
   // vars: 'all' 檢查所有變量的使用情況,包括全局范圍內的變量。這是默認設置。 args: 'after-used' 只有最后一個參數必須使用。例如,這允許您為函數使用兩個命名參數,並且只要您使用第二個參數,ESLint 就不會警告您第一個參數。這是默認設置。
   'no-useless-call' : 2, // 標記使用情況,Function.prototype.call()並且Function.prototype.apply()可以用正常的函數調用來替代
   'no-useless-computed-key' : 2, // 禁止不必要地使用計算屬性鍵
   'no-useless-constructor' : 2, // 在不改變類的工作方式的情況下安全地移除的類構造函數
   'no-useless-escape' : 0, // 禁用不必要的轉義字符
   'no-whitespace-before-property' : 2, // 如果對象的屬性位於同一行上,不允許圍繞點或在開頭括號之前留出空白
   'no-with' : 2, //禁用with
   'no-var' : 2, // 禁用var
   'one-var' : [2, { initialized: 'never' }], // 強制將變量聲明為每個函數(對於var)或塊(對於let和const)范圍一起聲明或單獨聲明。 initialized: 'never' 每個作用域要求多個變量聲明用於初始化變量
   'operator-linebreak' : [2, 'after' , { overrides: { '?' : 'before' , ':' : 'before' } }], // 實施一致的換行
   'padded-blocks' : [2, 'never' ], // 在塊內強制執行一致的空行填充
   'prefer-destructuring' : [ 'error' , { object: false , array: false }], // 此規則強制使用解構而不是通過成員表達式訪問屬性。
   'quotes' : [2, 'single' , { avoidEscape: true , allowTemplateLiterals: true }], // avoidEscape: true 允許字符串使用單引號或雙引號,只要字符串包含必須以其他方式轉義的引號 ;allowTemplateLiterals: true 允許字符串使用反引號
   'radix' : 2, //parseInt必須指定第二個參數
   'semi' : [2, 'never' ], // 不使用分號
   'semi-spacing' : [2, { before: false , after: true }], // 強制分號間隔
   'space-before-blocks' : [2, 'always' ], // 塊必須至少有一個先前的空間
   'space-before-function-paren' : [2, 'never' ], // 在(參數后面不允許任何空格
   'space-in-parens' : [2, 'never' ], // 禁止或要求(或)左邊的一個或多個空格
   'space-infix-ops' : 2, // 強制二元運算符左右各有一個空格
   'space-unary-ops' : [2, { words: true , nonwords: false }], // words: true 如:new,delete,typeof,void,yield 左右必須有空格 // nonwords: false 一元運算符,如:-,+,--,++,!,!!左右不能有空格
   'spaced-comment' : [2, 'always' , { markers: [ 'global' , 'globals' , 'eslint' , 'eslint-disable' , '*package' , '!' , ',' ] }], // 注釋開始后,此規則將強制間距的一致性//或/*
   'template-curly-spacing' : [2, 'never' ], // 不允許大括號內的空格
   'use-isnan' : 2, //禁止比較時使用NaN,只能用isNaN()
   'valid-typeof' : 2, //必須使用合法的typeof的值
   'wrap-iife' : [2, 'any' ], //立即執行函數表達式的小括號風格
   'yield-star-spacing' : [2, 'both' ], // 強制執行*周圍 yield*表達式的間距,兩側都必須有空格
   'yoda' : [2, 'never' ],
   'prefer-const' : 2, // 使用let關鍵字聲明的變量,但在初始分配后從未重新分配變量,應改為const聲明
   'object-curly-spacing' : [2, 'always' , { objectsInObjects: false }], // 不允許以對象元素開始和/或以對象元素結尾的對象的大括號內的間距
   'array-bracket-spacing' : [2, 'never' ] // 不允許數組括號內的空格
  }
}

2.2 eslint 安裝與配置

全局安裝 eslint

1
npm install -g eslint

全局安裝 Prettier

1
npm install -g prettier

vscode 插件市場搜索 eslint 和 prettier,下載並安裝。

vscode

編輯器 setting.json 中加如下配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/* 開啟保存時自動格式化 */
"editor.formatOnSave" : true ,
 
/* eslint的配置 */
"eslint.enable" : true ,
"eslint.run" : "onSave" ,
"eslint.options" : {
   "extensions" : [
    ".js" ,
    ".vue"
   ]
  },
  "editor.codeActionsOnSave" : {
   "source.fixAll.eslint" : true // 保存時自動修復
  },
  // 關閉 vscode 默認的檢查工具
  "html.validate.scripts" : false ,
  "javascript.validate.enable" : false ,
  "eslint.alwaysShowStatus" : true ,
  "eslint.format.enable" : true ,
  "scss.lint.duplicateProperties" : "error" ,
  "css.lint.duplicateProperties" : "error" ,
  "less.lint.zeroUnits" : "error" ,
  "eslint.validate" : [
   "javascript" ,
   "javascriptreact" ,
   "vue-html" ,
   "vue" ,
   "html"
  ],
 
/* prettier的配置 */
  "prettier.printWidth" : 120, // 超過最大值換行
  "prettier.tabWidth" : 2, // 縮進字節數
  "prettier.useTabs" : true , // 縮進使用tab
  "prettier.semi" : false , // 句尾添加分號
  "prettier.singleQuote" : true , // 使用單引號代替雙引號
  "prettier.proseWrap" : "preserve" , // 默認值。因為使用了一些折行敏感型的渲染器(如GitHub comment)而按照markdown文本樣式進行折行
  "prettier.arrowParens" : "avoid" , // (x) => {} 箭頭函數參數只有一個時是否要有小括號。avoid:省略括號
  "prettier.bracketSpacing" : true , // 在對象,數組括號與文字之間加空格 "{ foo: bar }"
  "prettier.endOfLine" : "auto" , // 結尾是 \n \r \n\r auto
  "prettier.htmlWhitespaceSensitivity" : "ignore" ,
  "prettier.ignorePath" : ".prettierignore" , // 不使用prettier格式化的文件填寫在項目的.prettierignore文件中
  "prettier.requireConfig" : false , // Require a "prettierconfig" to format prettier
  "prettier.trailingComma" : "none" , // 在對象或數組最后一個元素后面是否加逗號
 
/* 每種語言默認的格式化規則 */
  "[html]" : {
   "editor.defaultFormatter" : "esbenp.prettier-vscode"
  },
  "[css]" : {
   "editor.defaultFormatter" : "esbenp.prettier-vscode"
  },
  "[scss]" : {
   "editor.defaultFormatter" : "esbenp.prettier-vscode"
  },
  "[javascript]" : {
   "editor.defaultFormatter" : "esbenp.prettier-vscode"
  },
  "[vue]" : {
   "editor.defaultFormatter" : "esbenp.prettier-vscode"
  },
  "[json]" : {
   "editor.defaultFormatter" : "esbenp.prettier-vscode"
  },

使用 vuecli 創建項目時,不選擇 lint 選項。

在項目開發依賴中,加入@vue/cli-plugin-eslint、babel-eslint、eslint、eslint-plugin-vue、prettier、prettier-eslint 依賴

1
npm install @vue /cli-plugin-eslint babel-eslint eslint eslint-plugin-vue prettier prettier-eslint –-save-dev

在項目 package.json 內加入 lint 命令。

開發時,保存文件,即可按 prettier 規則格式化文件,並自動修復可修復的 issue,不能自動修復的,請根據提示,手動修復。

提示:vscode 已設置保存時格式化,但有時並不會格式化文件。已保存的文件還存在報錯的,請手動格式化,並修改相應問題后,再次保存。

提交代碼前,運行 npm run lint 代碼風格檢查,確認無誤后再進行提交。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

 

原文鏈接:https://segmentfault.com/a/1190000021598517

https://www.jb51.net/article/178614.htm


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM