[关闭]
@aqa510415008 2019-03-25T02:47:00.000000Z 字数 5823 阅读 1330

VS Code 保存代码,自动按照ESlint规范格式化代码设置

VSCode


前言

编辑器代码风格一致,是前端代码规范的一部分。同一个项目,或者同一个小组,保持代码风格一致很必要。就拿vue项目来说,之前做的几个项目,很多小伙伴代码格式化用的是vue-beautify ,这个格式化工具有个明显的缺点,就是三元不等式明明可以一行显示,非得格式化成3行,import用{}引入多个变量或者函数,非得格式化成好几行,看起来很是别扭。因此,好的格式化工具和团队代码风格一致,显得格外重要。我建议我们整个小组运用同一个编辑器,同一种代码校验,同一个格式化方式。下面我来介绍一下使用vscode+eslint 自动保存,自动格式化的一种方式!

eslint 自动格式化

先说一个前提吧,你在package.json中安装了eslint的依赖,不然配置无用。

例如如下依赖:

  1. "eslint": "^4.19.1",
  2. "eslint-friendly-formatter": "^4.0.1",
  3. "eslint-loader": "^2.0.0",
  4. "eslint-plugin-html": "^4.0.3",

上面说的是一个前提,下面来说一下具体的配置步骤:

首先,在我们项目跟目录添加.eslintrc.js 文件,用于校验代码,编写eslint相关规则,关于eslint的一些具体规则,请查看eslint文档

下面列一下我们项目中常用的eslint规则:

  1. module.exports = {
  2. root: true,
  3. parser: 'babel-eslint',
  4. parserOptions: {
  5. sourceType: 'module',
  6. "allowImportExportEverywhere": true //ignore eslint error: 'import' and 'export' may only appear at the top level
  7. },
  8. env: {
  9. browser: true,
  10. node: true,
  11. es6: true,
  12. },
  13. extends: 'eslint:recommended',
  14. // required to lint *.vue files
  15. plugins: [
  16. 'html',
  17. 'vue'
  18. ],
  19. // add your custom rules here
  20. //it is base on https://github.com/vuejs/eslint-config-vue
  21. 'rules': {
  22. 'accessor-pairs': 2,
  23. 'arrow-spacing': [2, {
  24. 'before': true,
  25. 'after': true
  26. }],
  27. 'block-spacing': [2, 'always'],
  28. 'brace-style': [2, '1tbs', {
  29. 'allowSingleLine': true
  30. }],
  31. 'camelcase': [0, {
  32. 'properties': 'always'
  33. }],
  34. 'comma-dangle': [2, 'never'],
  35. 'comma-spacing': [2, {
  36. 'before': false,
  37. 'after': true
  38. }],
  39. 'comma-style': [2, 'last'],
  40. 'constructor-super': 2,
  41. 'curly': [2, 'multi-line'],
  42. 'dot-location': [2, 'property'],
  43. 'eol-last': 2,
  44. 'eqeqeq': [2, 'allow-null'],
  45. 'generator-star-spacing': [2, {
  46. 'before': true,
  47. 'after': true
  48. }],
  49. 'handle-callback-err': [2, '^(err|error)$'],
  50. 'indent': [2, 2, {
  51. 'SwitchCase': 1
  52. }],
  53. 'jsx-quotes': [2, 'prefer-single'],
  54. 'key-spacing': [2, {
  55. 'beforeColon': false,
  56. 'afterColon': true
  57. }],
  58. 'keyword-spacing': [2, {
  59. 'before': true,
  60. 'after': true
  61. }],
  62. 'new-cap': [2, {
  63. 'newIsCap': true,
  64. 'capIsNew': false
  65. }],
  66. 'new-parens': 2,
  67. 'no-array-constructor': 2,
  68. 'no-caller': 2,
  69. 'no-console': 'off',
  70. 'no-class-assign': 2,
  71. 'no-cond-assign': 2,
  72. 'no-const-assign': 2,
  73. 'no-control-regex': 0,
  74. 'no-delete-var': 2,
  75. 'no-dupe-args': 2,
  76. 'no-dupe-class-members': 2,
  77. 'no-dupe-keys': 2,
  78. 'no-duplicate-case': 2,
  79. 'no-empty-character-class': 2,
  80. 'no-empty-pattern': 2,
  81. 'no-eval': 2,
  82. 'no-ex-assign': 2,
  83. 'no-extend-native': 2,
  84. 'no-extra-bind': 2,
  85. 'no-extra-boolean-cast': 2,
  86. 'no-extra-parens': [2, 'functions'],
  87. 'no-fallthrough': 2,
  88. 'no-floating-decimal': 2,
  89. 'no-func-assign': 2,
  90. 'no-implied-eval': 2,
  91. 'no-inner-declarations': [2, 'functions'],
  92. 'no-invalid-regexp': 2,
  93. 'no-irregular-whitespace': 2,
  94. 'no-iterator': 2,
  95. 'no-label-var': 2,
  96. 'no-labels': [2, {
  97. 'allowLoop': false,
  98. 'allowSwitch': false
  99. }],
  100. 'no-lone-blocks': 2,
  101. 'no-mixed-spaces-and-tabs': 2,
  102. 'no-multi-spaces': 2,
  103. 'no-multi-str': 2,
  104. 'no-multiple-empty-lines': [2, {
  105. 'max': 1
  106. }],
  107. 'no-native-reassign': 2,
  108. 'no-negated-in-lhs': 2,
  109. 'no-new-object': 2,
  110. 'no-new-require': 2,
  111. 'no-new-symbol': 2,
  112. 'no-new-wrappers': 2,
  113. 'no-obj-calls': 2,
  114. 'no-octal': 2,
  115. 'no-octal-escape': 2,
  116. 'no-path-concat': 2,
  117. 'no-proto': 2,
  118. 'no-redeclare': 2,
  119. 'no-regex-spaces': 2,
  120. 'no-return-assign': [2, 'except-parens'],
  121. 'no-self-assign': 2,
  122. 'no-self-compare': 2,
  123. 'no-sequences': 2,
  124. 'no-shadow-restricted-names': 2,
  125. 'no-spaced-func': 2,
  126. 'no-sparse-arrays': 2,
  127. 'no-this-before-super': 2,
  128. 'no-throw-literal': 2,
  129. 'no-trailing-spaces': 2,
  130. 'no-undef': 2,
  131. 'no-undef-init': 2,
  132. 'no-unexpected-multiline': 2,
  133. 'no-unmodified-loop-condition': 2,
  134. 'no-unneeded-ternary': [2, {
  135. 'defaultAssignment': false
  136. }],
  137. 'no-unreachable': 2,
  138. 'no-unsafe-finally': 2,
  139. 'no-unused-vars': [2, {
  140. 'vars': 'all',
  141. 'args': 'none'
  142. }],
  143. 'no-useless-call': 2,
  144. 'no-useless-computed-key': 2,
  145. 'no-useless-constructor': 2,
  146. 'no-useless-escape': 0,
  147. 'no-whitespace-before-property': 2,
  148. 'no-with': 2,
  149. 'one-var': [2, {
  150. 'initialized': 'never'
  151. }],
  152. 'operator-linebreak': [2, 'after', {
  153. 'overrides': {
  154. '?': 'before',
  155. ':': 'before'
  156. }
  157. }],
  158. 'padded-blocks': [2, 'never'],
  159. 'quotes': [2, 'single', {
  160. 'avoidEscape': true,
  161. 'allowTemplateLiterals': true
  162. }],
  163. 'semi': [2, 'never'],
  164. 'semi-spacing': [2, {
  165. 'before': false,
  166. 'after': true
  167. }],
  168. 'space-before-blocks': [2, 'always'],
  169. 'space-before-function-paren': [2, 'never'],
  170. 'space-in-parens': [2, 'never'],
  171. 'space-infix-ops': 2,
  172. 'space-unary-ops': [2, {
  173. 'words': true,
  174. 'nonwords': false
  175. }],
  176. 'spaced-comment': [2, 'always', {
  177. 'markers': ['global', 'globals', 'eslint', 'eslint-disable', '*package', '!', ',']
  178. }],
  179. 'template-curly-spacing': [2, 'never'],
  180. 'use-isnan': 2,
  181. 'valid-typeof': 2,
  182. 'wrap-iife': [2, 'any'],
  183. 'yield-star-spacing': [2, 'both'],
  184. 'yoda': [2, 'never'],
  185. 'prefer-const': 2,
  186. 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
  187. 'object-curly-spacing': [2, 'always', {
  188. objectsInObjects: false
  189. }],
  190. 'array-bracket-spacing': [2, 'never']
  191. }
  192. }

本项目基本规范是依托于 vue 官方的 eslint 规则 eslint-config-vue 做了少许的修改。你也可以进行一些属于你自己的定制,例如:目前使用缩进是2个空格,假如你觉得4个更顺眼,你可以如下修改

  1. 'indent': [4, 4, {
  2. 'SwitchCase': 2 // 针对switch case的缩进
  3. }],

其次,vscode中添加eslint和vetur插件:

如下图
image_1d6n0b7l5l6t1s0scee1v4i1hmsc.png-274.4kB

安装好了之后,会自动根据你上面配置的规则进行代码检查,不合格的会高亮显示,如下图:
image_1d6n0bp1e5ki197nsin664mtdp.png-80.2kB

经过上面步骤,目前保存还不能自动格式化,下面说下如何自动格式化!

第三,自动格式化设置,

1、window电脑:
文件 > 首选项 > 设置 打开 VSCode 配置文件
2、mac电脑
code>首选项 >设置

我的设置如下:

  1. {
  2. "editor.tabSize": 2,
  3. "files.associations": {
  4. "*.vue": "vue"
  5. },
  6. "eslint.autoFixOnSave": true,
  7. "eslint.options": {
  8. "extensions": [
  9. ".js",
  10. ".vue"
  11. ]
  12. },
  13. "eslint.validate": [
  14. "javascript",{
  15. "language": "vue",
  16. "autoFix": true
  17. },"html",
  18. "vue"
  19. ],
  20. "search.exclude": {
  21. "**/node_modules": true,
  22. "**/bower_components": true,
  23. "**/dist": true
  24. },
  25. "emmet.syntaxProfiles": {
  26. "javascript": "jsx",
  27. "vue": "html",
  28. "vue-html": "html"
  29. },
  30. "git.confirmSync": false,
  31. "window.zoomLevel": 0,
  32. "editor.renderWhitespace": "boundary",
  33. "editor.cursorBlinking": "smooth",
  34. "editor.minimap.enabled": true,
  35. "editor.minimap.renderCharacters": false,
  36. "editor.fontFamily": "'Droid Sans Mono', 'Courier New', monospace, 'Droid Sans Fallback'",
  37. "window.title": "${dirty}${activeEditorMedium}${separator}${rootName}",
  38. "editor.codeLens": true,
  39. "editor.snippetSuggestions": "top",
  40. }

这样,你就可以保存自动按照配置格式化代码了,体验如下:
image_1d6n0e0661t4f1e3rs4f1s5012h516.png-33.1kB

关闭eslint检查

关于关闭eslint,其实不是本节的内容,本节目的是开启,并自动格式化和检查!假如你实在是想关闭的话,设置方法如下:

1、vue create的项目

在vue.config.js中

  1. lintOnSave: false

2、以前的项目,vue init webpack的

config/index.js 文件。 将

  1. useEslint: true

设置为

  1. useEslint: false

其他推荐

其他团队也有自己的代码规范方式例如饿了么团队:https://www.npmjs.com/package/eslint-config-elemefe

vue团队:https://github.com/vuejs/eslint-config-vue

关于vscode扩展插件,目前通用的,不错的推荐看这篇文章:https://github.com/varHarrie/Dawn-Blossoms/issues/10

引用:https://www.haorooms.com/post/vscode_eslint

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注