在Vscode中配置Vetur,ESlint,Prettier(转载)

俗话说得好,工欲善其事必先利其器,想要熟练开发Vue项目,一个好的开发环境就是必不可少了,这里我就选用了vscode作为开发工具,毕竟vscode免费,还跨平台,应用范围也广,著名的vue开源项目:后台管理平台(vue-element-admin)的大神在文档中就推荐采用vscode+eslint,号称“绝对有种飞一般的感觉”。为了达到大神所说的效果,我们这就来研究一下如何在vscode中配置好eslint,寻找“飞一般”开发Vue的感觉。

 

 

1.vscode清除多余的插件,还原默认配置


对新手来说,vscode的扩展并不是越多越好的,特别是当你还不那么会调整配置的时候,我们还是一项一项加载安装,来处理。所以之前就先清理扩展和配置,清理扩展很简单,在扩展列表中,将那些插件逐项卸载就行,我就仅保留了vscode的中文包,以及Debugger for Chrome,这两个插件包,而环境配置方面,VSCode中有三种类型的配置文件:

默认配置文件(优先级最低)
用户配置文件(优先级次之)
工程配置文件 (优先级最高)
所以,我们只需要清除用户配置文件的值,以及工程配置文件的值,就是还原到默认配置了,我们可以用快捷键【ctrl+,】打开设置界面。如下图:

 

 

 

 

分别在选择用户和工作区的时候,点击右上角的打开设置的json文件,用户的json文件和工作区的json文件,虽然都是叫settings.json,但在路径上是不同的,一个是在项目目录的.vscode目录下,一个是在C盘的用户目录下的。将这两个文件中的配置都全部清除,仅保留{}。这样根据vscode的配置优先级来说,就是默认配置了。

 

 

 

 

 

2. 打开一个无ESlint的Vue项目


我们可以通过vue-cli创建一个项目,在配置插件时,不要勾选Linter / Formatter 选项,创建一个Vue项目,在vscode中打开这个项目的package.json文件,以及App.vue。

 

 

 

 

 

 

 

 

package.json一看就一目了然,dependencies中,就core-js,vue,vue-router,vuex这4个核心插件,而devDependencies中,就是必备的cli相关的4个核心插件和1个vue模版编译的插件,因为选择了CSS预处理,增加了sass的2个插件。

App.vue则显得白茫茫一片,没有任何高亮提示,以及语法色彩。

3.安装Vetur插件


在Vscode的扩展中搜索Vetur,我们来看一下Vetur的介绍说明,特征(features)就是语法突出显示,错误提示,格式化,自动完成等,QuickStart就是安装Vetur,然后打开一个github上的Veturpack代码,有setup说明的链接。这里我们使用vue-cli创建的项目代码来验证Vetur,就不需要在下载Veturpack代码了,我们来看一下Vuter官方的setup说明。支持sass,stylus ,eslint 3种扩展,sass和stylus都是CSS预处理的框架,目前都没有,先暂时不做设定,直接看效果吧。

 

 

 

 

 

vue文件和js文件中,都有语法高亮表示了,但是没有自动格式化。我们需要在vscode中修改一项配置,如下图

 

 

 

或者在settings.json文件中,增加一项

1 //settings.json
2 {
3     .....
4  
5     "editor.formatOnSave": true, // 在保存时自动格式化
6     "vetur.format.options.tabSize": 4,
7 }

 


再打开App.vue后,可以分别对<template>和<style>中的代码,随意增加缩进,之后再按【ctrl+s】进行保存时,就可以看到vue文件中的<template>都自动改为4格缩进处理,<style>和<script>都没有处理,如果需要对vue文件中的script和style都统一缩进格式,需要打开vetur.format.styleInitialIndent,vetur.format.scriptInitialIndent这两项,都设为true即可。

1 // settings.json
2 {
3   ....
4   "vetur.format.styleInitialIndent": true,
5   "vetur.format.scriptInitialIndent": true,
6  
7 }

 


接着打开main.js,做同样的操作,却没有变化,因为Vetur这个插件formatter只是针对.vue文件的。

下一步,我们开始配置Vetur中的风格处理,无论是Vetur官网,还是vscode设置中显示,vetur的formatter大多采用的Prettier风格。有2个地方可以进行配置prettier风格参数,一个是vscode的配置文件settings.json,还有一个就是在项目根目录下创建.prettierrc文件,文件内容也是采用json格式,但是需要注意:根据官网的说明,一旦在项目的根目录下存在.prettierrc文件,则settings.json中的prettier配置就会无效。

 1 // settings.json
 2  
 3 {
 4   ......
 5  
 6   "vetur.format.defaultFormatterOptions": {
 7     "prettier": {
 8       // Prettier option here
 9       "trailingComma": "es5", // 多行时,尽可能打印尾随的逗号
10       "tabWidth": 4, // 会忽略vetur的tabSize配置
11       "useTabs": false, // 是否利用tab替代空格
12       "semi": true, // 句尾是否加;
13       "singleQuote": true, // 使用单引号而不是双引号
14       "arrowParens": "avoid", // allow paren-less arrow functions 箭头函数的参数使用圆括号
15     }
16   }
17 }

 


从上面可以看到,prettier下有个配置tabWidth和vetur.format有个配置tabSize,都是讲tab缩进的。这两个属性大多数时候都是一样的,但是在一个地方却是不一样的。我把tabSize设为2,tabWidth设为4,我们再看App.vue文件

 

 

 

用红框标出的几个地方的缩进都是2格,而其余的地方都是4格。具体怎么使用,就看各自的爱好了。这里我更喜欢用.prettierrc文件的方式来替代settings.json中的配置,因为这样,.prettierrc的格式会跟着项目一起,统一整个项目组的开发风格。

1 // .prettierrc
2 {
3     "tabWidth": 4, // 会忽略vetur的tabSize配置
4     "useTabs": false, // 是否利用tab替代空格
5     "semi":false, // 句尾是否加;
6     "trailingComma": "none", // es5多行时,尽可能打印尾随的逗号
7     "arrowParens": "avoid", // allow paren-less arrow functions 箭头函数的参数使用圆括号
8     "vueIndentScriptAndStyle":true,
9 }

 


但是实际测试下来,.prettierrc中只有少数几个配置是有效的,有些配置并没有起效,倒是settings.json中的配置都有效,或许等安装了prettier的专属扩展后,.prettierrc文件才会完全有效吧,暂时先采用settings.json的配置吧。

4.安装ESLint插件


在搞定了Vetur之后,我们来安装ESlint,在扩展商店搜索eslint,很容易就找到这个插件,相关的插件还有很多,例如Prettier ESLint等,我们一个一个来,先搞定ESLint再说,看eslint插件的说明,单单vscode中安装eslint是不够的,还需要项目中安装eslint依赖包。也就是需要在package.json中需要eslint,而eslint是针对很多种开发语言的,针对每一个开发语言都有一个独立的插件,对应vue的就是eslint-plugin-vue了,我们需要在项目目录下执行下面语句来执行安装。

> npm install -D eslint eslint-plugin-vue --registry=https://registry.npm.taobao.org

 

安装完eslint和eslint-plugin-vue之后,我们还需要创建eslint的配置文件,建议在项目根目录下,用命令行方式执行eslint --init来创建配置文件,因为生产的.eslintrc.js文件就在你当前执行命令的目录下。注意:我之前想在vscode的终端上直接执行命令,可惜提示什么策略不对,就是权限不足,懒得再去搞什么配置策略,直接用cmd命令,在项目目录下执行就行。

> .\node_modules\.bin\eslint --init

 

过程有几个选项,问题都不大,problems表示To check syntax and find problems,esm表示Javascript Modules,剩下的更直观,因为选择了vue作为项目框架,就问你要不要安装eslint-plugin-vue的插件,这里装不装都不影响,都可以之后再处理。

√ How would you like to use ESLint? · problems
√ What type of modules does your project use? · esm
√ Which framework does your project use? · vue
√ Does your project use TypeScript? · No / Yes
√ Where does your code run? · browser, node
√ What format do you want your config file to be in? · JavaScript
The config that you've selected requires the following dependencies:

eslint-plugin-vue@latest
√ Would you like to install them now with npm? · No / Yes
Installing eslint-plugin-vue@latest

Successfully created .eslintrc.js file in XXXXXXXX

 

这样就创建号eslint的配置文件了,不过,我闲这个过程太负责,还是直接手动在项目根目录下创建.eslintrc.js文件,然后网上随便找一篇配置文档过来就行,效果一样,而且eslint --init创建的配置文件,某些项可能版本太新,对应的其他插件版本没有跟上,还会报错。例如:init初始化的配置文件,env下有一项es2021,吓了我一大跳,不都是es6吗?哪来2021了,官网看看都没见这个配置说明,网上一搜,还有人爆出这个和eslint-config-standard 有冲突。不过我们先用来说明一下,还是问题不大了。

 1 // .eslintrc.js
 2 module.exports = {
 3     "env": {
 4         "browser": true,
 5         "es2021": true,    // 还是改为"es6": true
 6         "node": true
 7     },
 8     "extends": [
 9         "eslint:recommended",
10         "plugin:vue/essential"
11     ],
12     "parserOptions": {
13         "ecmaVersion": 12,
14         "sourceType": "module"
15     },
16     "plugins": [
17         "vue"
18     ],
19     "rules": {
20     }
21 };

 

除了rules之外的几个配置的说明,可以参考官网上的说明:http://eslint.cn/docs/user-guide/configuring,在这里就仅说明一下,使用到的配置。我们简单修改一下,添加一些说明,配上两个最简单的规则,以便eslint先执行起来。

 1 // .eslintrc.js
 2 module.exports = {
 3     "env": {    //用来预定义全局环境变量,常用的有browser,es6,node,jest,jquery
 4         "browser": true,
 5         "es6": true,
 6         "node": true
 7     },
 8     
 9     "extends": [
10         "eslint:recommended",
11         "plugin:vue/essential"
12     ],
13     "parserOptions": {  // 支持的 JavaScript 语言选项
14         "parser": "babel-eslint",   // 默认使用Espree作为其解析器,除此之外就Esprima,Babel-ESLint,@typescript-eslint/parser
15         "ecmaVersion": 12, // ECMAScript 版本,默认设置为 3,5(默认),也可以年份,2015(同 6),2012(as 12)
16         "sourceType": "module"  // "script" (默认) 或 "module"(如果你的代码是 ECMAScript 模块)
17     },
18     "plugins": [    //eslint支持使用第三方插件,需要npm先安装,后使用
19         "vue"   // 可以用package的名称,eslint-plugin-vue,也可以省略eslint-plugin-,直接填写vue
20     ],
21     "rules": {
22         // 强制使用单引号 
23         'quotes': ['error', 'single'],
24         // 在块级作用域外访问块内定义的变量是否报错提示 
25         'block-scoped-var': 0,
26     }
27 };

 

由于我们选择的parser的值为babel-eslint,需要通过npm安装好这个依赖包.

> npm i -D babel-eslint --registry=https://registry.npm.taobao.org

 

安装完这个,我们就可以在vscode中发现,eslint已经生效了。为了避免eslint对没必要的文件也进行检查,添加一个.eslintignore文件,保存需要略过的文件和目录

# .eslintignore
build/*.js
src/assets
public
dist
.eslintrc.js

 

下一步需要在vscode中增加eslint的相关配置。

 1 // settings.json
 2 {
 3 .......
 4  
 5   // 指定eslint校验的文件类型
 6   "eslint.validate": [
 7     "javascript",
 8     "javascriptreact",
 9     "html",
10     "vue"
11   ],
12   // "eslint.autoFixOnSave": true,
13   "editor.codeActionsOnSave": {
14     "source.fixAll.eslint": true
15   },
16   "eslint.run": "onSave",   // 保存就校验
17 }

 

接下来,在package.json中补上eslint校验的命令行,我们在package.json中,找到scripts节点,增加一行新的启动命令 "lint": "vue-cli-service lint"。

 1 //package.json
 2 {
 3   ......
 4  
 5   "scripts": {
 6     "serve": "vue-cli-service serve",
 7     "build": "vue-cli-service build",
 8     "lint": "vue-cli-service lint"
 9   },
10  
11   ......
12 }

 

这样,在vscode的npm脚本中就多了一行启动方式。尝试启动,结果系统提示错误,网上查了一下,又对照了vue-cli创建的项目中带eslint的配置,发现原来少一个插件包:@vue/cli-plugin-eslint,在项目根目录下执行npm安装

> npm i -D @vue/cli-plugin-eslint --registry=https://registry.npm.taobao.org


补上这个插件包,再次执行就成功了,这样ESLint算是安装完成了。我们把网上copy来的eslint的rules放入.eslintrc.js中。也可以根据自己的习惯来修改这些规则,注意所有规则第一个值适用下面定义,0或off:关闭;1或warn:提示警告,但不影响代码存在;2或error:提示错误,执行ESLint校验会导致失败。完整的.eslintrc.js如下:

  1 // .eslintrc.js
  2 module.exports = {
  3     "root": true,    // 表明这就是根目录了,停止去父级目录中寻找配置
  4     "env": {    //用来预定义全局环境变量,常用的有browser,es6,node,jest,jquery
  5         "browser": true,
  6         "es6": true,
  7         "node": true
  8     },
  9     "parserOptions": {  // 支持的 JavaScript 语言选项
 10         "parser": "babel-eslint",   // 默认使用Espree作为其解析器,除此之外就Esprima,Babel-ESLint,@typescript-eslint/parser
 11         "ecmaVersion": 12, // ECMAScript 版本,默认设置为 3,5(默认),也可以年份,2015(同 6),2012(as 12)
 12         "sourceType": "module"  // "script" (默认) 或 "module"(如果你的代码是 ECMAScript 模块)
 13     },
 14     "extends": [    // 规则模版
 15         "eslint:recommended",   // 启用一系列核心规则,
 16         "plugin:vue/essential",  // 启用eslint vue插件的规则模版,base,essential,strongly-recommended,recommended(最严)
 17     ],
 18     "plugins": [    //eslint支持使用第三方插件,需要npm先安装,后使用
 19         "vue",   // 可以用package的名称,eslint-plugin-vue,也可以省略eslint-plugin-,直接填写vue
 20     ],
 21     "rules": {  //补充规则
 22         // 强制使用单引号
 23         'quotes': ['error', 'single'],
 24         // 在块级作用域外访问块内定义的变量是否报错提示
 25         'block-scoped-var': 0,
 26         "vue/max-attributes-per-line": 0,
 27         "vue/singleline-html-element-content-newline": "off",
 28         "vue/multiline-html-element-content-newline": "off",
 29         "vue/name-property-casing": ["error", "PascalCase"],
 30         "vue/no-v-html": "off",
 31         'accessor-pairs': 2,
 32         'arrow-spacing': [2, {
 33             'before': true,
 34             'after': true
 35         }],
 36         'block-spacing': [2, 'always'],
 37         'brace-style': [2, '1tbs', {
 38             'allowSingleLine': true
 39         }],
 40         'camelcase': [0, {
 41             'properties': 'always'
 42         }],
 43         'comma-dangle': 0,
 44         'comma-spacing': [2, {
 45             'before': false,
 46             'after': true
 47         }],
 48         'comma-style': [2, 'last'],
 49         'constructor-super': 2,
 50         'curly': [2, 'multi-line'],
 51         'dot-location': [2, 'property'],
 52         'eol-last': 2,
 53         'eqeqeq': ["error", "always", { "null": "ignore" }],
 54         'generator-star-spacing': [2, {
 55             'before': true,
 56             'after': true
 57         }],
 58         'handle-callback-err': [2, '^(err|error)$'],
 59         'indent': [2, 4, {
 60             'SwitchCase': 1
 61         }],
 62         'jsx-quotes': [2, 'prefer-single'],
 63         'key-spacing': [2, {
 64             'beforeColon': false,
 65             'afterColon': true
 66         }],
 67         'keyword-spacing': [2, {
 68             'before': true,
 69             'after': true
 70         }],
 71         'new-cap': [2, {
 72             'newIsCap': true,
 73             'capIsNew': false
 74         }],
 75         'new-parens': 2,
 76         'no-array-constructor': 2,
 77         'no-caller': 2,
 78         'no-console': 'off',
 79         'no-class-assign': 2,
 80         'no-cond-assign': 2,
 81         'no-const-assign': 2,
 82         'no-control-regex': 0,
 83         'no-delete-var': 2,
 84         'no-dupe-args': 2,
 85         'no-dupe-class-members': 2,
 86         'no-dupe-keys': 2,
 87         'no-duplicate-case': 2,
 88         'no-empty-character-class': 2,
 89         'no-empty-pattern': 2,
 90         'no-eval': 2,
 91         'no-ex-assign': 2,
 92         'no-extend-native': 2,
 93         'no-extra-bind': 2,
 94         'no-extra-boolean-cast': 2,
 95         'no-extra-parens': [2, 'functions'],
 96         'no-fallthrough': 2,
 97         'no-floating-decimal': 2,
 98         'no-func-assign': 2,
 99         'no-implied-eval': 2,
100         'no-inner-declarations': [2, 'functions'],
101         'no-invalid-regexp': 2,
102         'no-irregular-whitespace': 2,
103         'no-iterator': 2,
104         'no-label-var': 2,
105         'no-labels': [2, {
106             'allowLoop': false,
107             'allowSwitch': false
108         }],
109         'no-lone-blocks': 2,
110         'no-mixed-spaces-and-tabs': 2,
111         'no-multi-spaces': 2,
112         'no-multi-str': 2,
113         'no-multiple-empty-lines': [2, {
114             'max': 1
115         }],
116         'no-native-reassign': 2,
117         'no-negated-in-lhs': 2,
118         'no-new-object': 2,
119         'no-new-require': 2,
120         'no-new-symbol': 2,
121         'no-new-wrappers': 2,
122         'no-obj-calls': 2,
123         'no-octal': 2,
124         'no-octal-escape': 2,
125         'no-path-concat': 2,
126         'no-proto': 2,
127         'no-redeclare': 2,
128         'no-regex-spaces': 2,
129         'no-return-assign': [2, 'except-parens'],
130         'no-self-assign': 2,
131         'no-self-compare': 2,
132         'no-sequences': 2,
133         'no-shadow-restricted-names': 2,
134         'no-spaced-func': 2,
135         'no-sparse-arrays': 2,
136         'no-this-before-super': 2,
137         'no-throw-literal': 2,
138         'no-trailing-spaces': 2,
139         'no-undef': 2,
140         'no-undef-init': 2,
141         'no-unexpected-multiline': 2,
142         'no-unmodified-loop-condition': 2,
143         'no-unneeded-ternary': [2, {
144             'defaultAssignment': false
145         }],
146         'no-unreachable': 2,
147         'no-unsafe-finally': 2,
148         'no-unused-vars': [2, {
149             'vars': 'all',
150             'args': 'none'
151         }],
152         'no-useless-call': 2,
153         'no-useless-computed-key': 2,
154         'no-useless-constructor': 2,
155         'no-useless-escape': 0,
156         'no-whitespace-before-property': 2,
157         'no-with': 2,
158         'one-var': [2, {
159             'initialized': 'never'
160         }],
161         'operator-linebreak': [2, 'after', {
162             'overrides': {
163                 '?': 'before',
164                 ':': 'before'
165             }
166         }],
167         'padded-blocks': [2, 'never'],
168         'quotes': [2, 'single', {
169             'avoidEscape': true,
170             'allowTemplateLiterals': true
171         }],
172         'semi': [2, 'never'],
173         'semi-spacing': [2, {
174             'before': false,
175             'after': true
176         }],
177         'space-before-blocks': [2, 'always'],
178         'space-before-function-paren': [2, 'never'],
179         'space-in-parens': [2, 'never'],
180         'space-infix-ops': 2,
181         'space-unary-ops': [2, {
182             'words': true,
183             'nonwords': false
184         }],
185         'spaced-comment': [2, 'always', {
186             'markers': ['global', 'globals', 'eslint', 'eslint-disable', '*package', '!', ',']
187         }],
188         'template-curly-spacing': [2, 'never'],
189         'use-isnan': 2,
190         'valid-typeof': 2,
191         'wrap-iife': [2, 'any'],
192         'yield-star-spacing': [2, 'both'],
193         'yoda': [2, 'never'],
194         'prefer-const': 2,
195         'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
196         'object-curly-spacing': [2, 'always', {
197             objectsInObjects: false
198         }],
199         'array-bracket-spacing': [2, 'never']
200     }
201 };

 

然后,就发现有不少冲突了,先暂时不管,我们来进行下一步,用Prettier来格式化代码。

5.安装Prettier插件


还是在vscode的扩展商店搜索prettier,结果好几个都叫Prettier - Code formatter的插件,选个发布者叫Perttier,这个应该算标准的吧。看这个插件说明,也是需要通过npm安装prettier依赖包的。如果我们要把prettier风格替代eslint的代码格式检查,就还需要安装eslint-plugin-prettier,如同eslint的vue插件一样,如果eslint和prettier出现了冲突,就需要安装eslint-config-prettier插件了。

> npm install prettier eslint-plugin-prettier eslint-config-prettier -D --save-exact --registry=https://registry.npm.taobao.org

 

安装完prettier的相关依赖包之后,调整.eslintrc.js文件

1 extends: 'prettier' // 使用的时候需要确保,这个配置在extends的最后一项。例如以下形式:
2 //.eslintrc.js
3 {
4   "extends": [    // 规则模版
5         "eslint:recommended",   
6         "plugin:vue/essential",  
7         "prettier"
8     ],
9 }

 

自定义规则使用 eslint-plugin-* 的命名,使用时写成

1   plugins: ["prettier"],
2   rules: {
3     "prettier/prettier": "error" // 表示被 prettier 标记的地方抛出错误
4   }

 

上面两项配置可以简化成

{
  "extends": ["plugin:prettier/recommended"]
}

 

最终,在上面的.eslintrc.js文件上,增加prettier新增部分的配置即可

 1 //.eslintrc.js
 2 module.exports = {
 3     "root": true, 
 4     // .....  
 5  
 6     "extends": [    // 规则模版
 7         "eslint:recommended",   // 启用一系列核心规则,
 8         "plugin:vue/essential",  // 启用eslint vue插件的规则模版,base,essential,strongly-recommended,recommended(最严)
 9         "plugin:prettier/recommended"    // prettier新增
10     ],
11     "plugins": [    //eslint支持使用第三方插件,需要npm先安装,后使用
12         "vue",   // 可以用package的名称,eslint-plugin-vue,也可以省略eslint-plugin-,直接填写vue
13         "prettier" // prettier新增
14     ],
15     // .....
16  
17 }

 

因为安装了Perttier,以及eslint-plugin-prettier,这里就会需要用到项目根目录下的prettier的配置文件,根据官方介绍,prettier的配置文件支持多种命名和后缀,具体参考https://prettier.io/docs/en/configuration.html,因为是初学者,想要在配置文件中可以合法的加入注释,我选用.prettierrc.js命名。

 1 // .prettierrc.js
 2 module.exports = {
 3     tabWidth: 4, // 会忽略vetur的tabSize配置
 4     useTabs: false, // 是否利用tab替代空格
 5     singleQuote: true, // 使用单引号而不是双引号
 6     jsxSingleQuote: true,
 7     semi: false, // 句尾是否加;
 8     trailingComma: 'es5', // es5多行时,尽可能打印尾随的逗号
 9     arrowParens: 'avoid', // allow paren-less arrow functions 箭头函数的参数使用圆括号
10     endOfLine: 'lf', // 换行符校验
11     jsxBracketSameLine: true, // #多行JSX中的>放置在最后一行的结尾,而不是另起一行(默认false)
12     bracketSpacing: true,
13     proseWrap: 'always', // 换行,always:超过printWidth就换行,never:不换行,preserve:按照原样处理
14     printWidth: 220,
15 }
16  


这样基本可以说,Perttier的插件配置也算好了,但是vscode提示各种警报,我们开始来修正提示的错误,有些东西一概就好了,但是有些错误,在编辑器中通过autofix修正了eslint的错误,但是【ctrl+s】保存后,又自动变成错误格式了,这就是风格和校验之间的规则没有统一,出现了冲突,这个时候需要我们来准确配置相关的规则,并明确我们想要的规则到底是什么,有些规则并没有对错,仅仅只是习惯问题而已,例如尾项有没有",",eslint标准是没有,可是我习惯有,又例如html属性是否换行?又不换行的标准,有每一个属性一行的风格,还有超过长度才换行的标准,等等,这些就是我们接下来要搞定的冲突了。

6.解决Vetur,ESLint,Perttier之间的冲突


在解决eslint,vetur,perttier之间的冲突之前,我们现需要明确,vetur,eslint,perttier这些各自擅长什么?你打算让他们做什么?

ESLint主要用来解决JS的风格和代码语法检查,Perttier就是纯粹的代码风格处理的,支持js,ts,jsx,json,css,scss,vue,markdown等。这两个在Js文件上比较容易统一,Perttier来处理JS代码风格,eslint来检查JS代码语法,但是在vue文件上,有html格式的<template>部分,有js的<script>部分,还有处理css的<style>部分,就擅长处理就需要vetur来设定了,vetur主要就是来处理vue文件的,本身也支持对template,script,style这3部分分别指定风格处理模版,vetue自身也支持prettier,js-beautify-html等多种风格,但是vetur不负责语法检查,vue中的script的语法检查,还是需要eslint,或者prettier-eslint来处理。这样,在vue文件的风格处理上有2中选择,一种就是全部交给perttier来处理,prettier对<template>,<script>,<style>都可以处理,不过坏处是template,js,css的规则必须一致,毕竟依赖同一份perttier规则。还有一种是交给vetur来处理,通过vetur的配置,来分别指定template,script, style的处理风格,这样的话,通常template部分就会交给js-beautify-html模版,script交给prettir-eslint模版,style交给prettier。

先来说由vetur来处理vue文件的settings.json的配置。完整的settings.json如下

 

 1 // settings.json
 2 {
 3     "workbench.startupEditor": "newUntitledFile",
 4     "files.autoSave": "off",    // 关闭文件自动保存,避免开发时候页面变化
 5     "editor.tabSize": 4, // tab距离
 6     "editor.formatOnSave": true, // 在保存时自动格式化
 7     "editor.minimap.enabled": false, // 关闭右侧快速预览
 8     "files.eol": "\n", // 设定文件的换行符,\n(linux模式)或\r\n(win模式)
 9     "editor.detectIndentation": false, // 关闭vscode的缩进检查
10     "editor.fontSize": 14, //设置文字大小
11     "editor.lineHeight": 0, //设置文字行高
12     "editor.lineNumbers": "on", //开启行数提示
13     "editor.quickSuggestions": {
14         //开启自动显示建议
15         "other": true,
16         "comments": true,
17         "strings": true
18     },
19     "window.zoomLevel": 0, // 调整窗口的缩放级别
20     //根据文件后缀名定义vue文件类型
21     "files.associations": {
22         "*.vue": "vue"
23     },
24     // 为各类文件制定Fatmatter插件
25     "[vue]": {
26         // "editor.defaultFormatter": "esbenp.prettier-vscode"  // 采用prettier处理格式化
27         "editor.defaultFormatter": "octref.vetur" // 采用vetur来处理Fatmatter
28     },
29     "[javascript]": {
30         "editor.defaultFormatter": "esbenp.prettier-vscode"
31     },
32     "[json]": {
33         "editor.defaultFormatter": "esbenp.prettier-vscode"
34     },
35     "[jsonc]": {
36         "editor.defaultFormatter": "vscode.json-language-features"
37     },
38     // Vetur 的各类设定,仅当上面[vue]的editor.defaultFormatter的值为octref.vetur的时候,才起效
39     "vetur.format.options.tabSize": 4,
40     "vetur.format.styleInitialIndent": false, // 关闭vue中script标签初始缩进,开启会和eslint的缩进校验冲突
41     "vetur.format.scriptInitialIndent": false, // 关闭vue中style标签初始缩进,开启会和eslint的缩进校验冲突
42     "vetur.format.defaultFormatter.html": "js-beautify-html", // 针对vue中的template部分的风格模版,也可以是:prettier
43     "vetur.format.defaultFormatter.js": "prettier-eslint", // 针对vue中的script部分的风格模版,或者prettier
44     "vetur.format.defaultFormatter.css": "prettier", // 针对vue中的style部分的风格模版
45     "vetur.format.defaultFormatterOptions": {
46         "js-beautify-html": { // 配置不能和prettier的配置冲突,eslint校验的时候采用的prettier的风格
47             // 给js-beautify-html设置属性隔断
48             "wrap_line_length": 220, //换行长度
49             // 属性换行
50             // 对属性进行换行。
51             // - auto: 仅在超出行长度时才对属性进行换行。
52             // - force: 对除第一个属性外的其他每个属性进行换行。
53             // - force-aligned: 对除第一个属性外的其他每个属性进行换行,并保持对齐。
54             // - force-expand-multiline: 对每个属性进行换行。
55             // - aligned-multiple: 当超出折行长度时,将属性进行垂直对齐。
56             "wrap_attributes": "auto",
57             // Maximum number of line breaks to be preserved in one chunk (0 disables)
58             // "max_preserve_newlines": 0,
59             "end_with_newline": false
60         },
61         "prettyhtml": {
62             "printWidth": 220,
63             "singleQuote": false,
64             "wrapAttributes": false,
65             "sortAttributes": false
66         }
67         // "prettier": {
68         //         // Prettier option here
69         //         "printWidth": 120,
70         //         "trailingComma": "none", // 多行时,尽可能打印尾随的逗号
71         //         "tabWidth": 4, // 会忽略vetur的tabSize配置
72         //         "useTabs": false, // 是否利用tab替代空格
73         //         "semi": false, // 句尾是否加;
74         //         "singleQuote": true, // 使用单引号而不是双引号
75         //         "arrowParens": "avoid", // allow paren-less arrow functions 箭头函数的参数使用圆括号
76         // }
77     },
78     // ESLint 的相关配置
79     "eslint.validate": [
80         "javascript",
81         "javascriptreact",
82         "vue"
83     ], // eslint校验的文件类型
84     // 该属性相当于配置js文件的操作
85     // "[javascript]": {
86     //   "editor.formatOnSave": true,
87     //   "editor.defaultFormatter": "esbenp.prettier-vscode"
88     // },
89     // "eslint.autoFixOnSave": true,  很多插件提示这么设定,但实际vscode中已经弃用这个设置,改用下面的方式。
90     "editor.codeActionsOnSave": {
91         // 保存时触发的事件
92         "source.fixAll.eslint": true // 自动fix eslint
93     },
94     "eslint.run": "onSave", // 保存就校验
95     // 函数名后增加空格
96     "javascript.format.insertSpaceBeforeFunctionParenthesis": true,
97     "javascript.format.insertSpaceAfterFunctionKeywordForAnonymousFunctions": true,
98 }

除了vscode的settings.json之外,还有.prettierrc.js和.eslintrc.js都维持上面的配置即可,这里我在js-beautify-html的相关配置和很多帖子上的不一样,主要是我习惯标签和属性在一行,而不喜欢每个属性一行,另外,我习惯tab距离为4,而是eslint标准的2格。到这里为止,基本来说Vetur,ESLint,Prettier都算是配置好了,也应该解决了相互之间的冲突了。

当然,可能每个人在这中间的过程中,会遇到一些各自不同的问题,例如我就在过程中,出现了一个换行符的报错信息,vscode中即便设置了files.eol:"\n",在prettier的配置文件中,添加了endOfLine: 'lf',规则也无效,最终网上找了一堆,安装一个EditorConfig的插件,并在项目根目录下创建一个.editorconfig的文件,才解决了换行符的问题。

 1 # https://editorconfig.org
 2 root = true
 3  
 4 [*]
 5 charset = utf-8
 6 indent_style = space
 7 indent_size = 4
 8 end_of_line = lf
 9 insert_final_newline = true
10 trim_trailing_whitespace = true
11  
12 [*.md]
13 insert_final_newline = false
14 trim_trailing_whitespace = false

完成了采用Vetur处理vue的配置,再来试试用Prettier来代替vetur的配置。因为之前说过,vscode的配置优先顺序是:工程的配置>用户定义的配置>默认配置,所以我们不用修改vscode中的用户定义的配置文件,直接打开工程配置文件,也就是在项目的根目录下,有个.vscode的目录,里面也有一个settings.json的文件,这个文件就是用来存储项目工程的配置信息的。只需要修改一个设定即可,如下图

1 // .vscode\settings.json
2 {
3     "[vue]": {
4         "editor.defaultFormatter": "esbenp.prettier-vscode" // 采用prettier处理格式化
5         // "editor.defaultFormatter": "octref.vetur" // 采用vetur来处理Fatmatter
6     },
7 }

 

那么之前在用户自定义配置的settings.json中,vetur.format.XXXX都将变得无效,我们可以通过修改.prettierrc.js文件中的一些配置,这些配置即便和之前的vetur.format.XXXX中的某项冲突,也不会像之前那样显示冲突了,而是都按照.prettierrc.js中的配置来格式化代码了。具体的效果,各位可以自己尝试一下,不过,作者在尝试修改.prettierrc.js中的配置时候,感觉很多配置效果响应并不怎么好,后来就清除了大多数的prettier的配置,仅保留了大多数帖子上留着的少数几个配置,其余都清楚了,不是说没用了,而是都属于默认值,写不写都一样。

1 // .prettierrc.js
2 module.exports = {
3     singleQuote: true, // 使用单引号而不是双引号
4     semi: false, // 句尾是否加;
5     printWidth: 120,
6     proseWrap: 'preserve',
7     tabWidth: 4,
8 }

 

由此看来,很多人推荐采用Vetur的js-beautify-html来处理template部分,只需要注意一些相关的配置一致性就行。更多的规则配置看官网

eslint规则:http://eslint.cn/docs/rules/
eslint-plugin-vue规则:https://eslint.vuejs.org/rules/
prettier规则:https://prettier.io/docs/en/options.html
js-beautify-html规则:https://beautifier.io/
对规则别人发布的规则配置不满意的,去官网查了自己改。

补充:

之后,为了保证所有项目都可以使用prettier的配置,打算删除.prettierrc.js文件,将perttier的配置,放入settings.json中,在vscode安装了prettier的扩展后,就可以在settings.json中,通过prettier.XXXX的方式设定prettier的规则,但是实际效果测试下来,settings.json中的prettier的配置,针对选择的是esbenp.prettier-vscode的是有效的,但是对于eslint插件中prettier-eslint就无效了,必须采用.prettierrc.js的方式才能通用。

参考资源:

https://blog.csdn.net/peade/article/details/103865934

https://www.cnblogs.com/xjnotxj/p/10828183.html

https://blog.csdn.net/qq_15601471/article/details/99985647

https://www.cnblogs.com/matd/p/10972319.html

https://prettier.io/docs/en/configuration.html

https://blog.csdn.net/u010108836/article/details/107873990

https://www.cnblogs.com/sunjinggege/p/8809536.html

https://www.cnblogs.com/little-ab/articles/9521771.html

https://eslint.vuejs.org/rules/max-attributes-per-line.html
————————————————
版权声明:本文为CSDN博主「Myron.Maoyz」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/justflow/article/details/109897364

 

vsCode格式化插件

 

ESlint:是用来统一JavaScript代码风格的工具,不包含css、html等

背景

近来研究前端,然后一直在百度上找VScode格式化(ESlint)的插件,结果找了半天都不靠谱。目前没有一个可以格式化html、css、符合ESlint的js、vue的插件,所以自己东拼西凑加实践找到解决方法。

一、安装插件

 

 

1)ESlint:javascript代码检测工具,可以配置每次保存时格式化js,但每次保存只格式化一点点,你得连续按住Ctrl+S好几次,才格式化好,自行体会~~
2)vetur:可以格式化html、标准css(有分号 、大括号的那种)、标准js(有分号 、双引号的那种)、vue文件,
但是!格式化的标准js文件不符合ESlint规范,会给你加上双引号、分号等,像这样

3)Prettier - Code formatter:只关注格式化,并不具有eslint检查语法等能力,只关心格式化文件(最大长度、混合标签和空格、引用样式等),包括JavaScript · Flow · TypeScript · CSS · SCSS · Less · JSX · Vue · GraphQL · JSON · Markdown
4)Manta's Stylus Supremacy: 格式化stylus的插件(不用就不装),因为vetur会把css格式化有分号 、大括号的那种,此插件会把css格式化成stylus风格,像这样

二、配置settings.json信息

File->Preference->Settings【也可以快捷键 ctr + ,(window系统) 直接打开】

 

 

现在看到的是界面配置模式,点击右上角的大括号(如下图),可以打开 settings.json 文件。

 

 粘贴以下代码,保存即可

 

第二部分内容转载链接:https://www.cnblogs.com/zhoudawei/p/11198781.html

 

 最后,附上 我已经在用的配置:

 

 1 {
 2     // #值设置为true时,每次保存的时候自动格式化;值设置为false时,代码格式化请按shift+alt+F
 3     "editor.formatOnSave": false,
 4     //设置tab的缩进为2
 5     "editor.tabSize": 2,
 6     // #每次保存的时候将代码按eslint格式进行修复
 7     "editor.codeActionsOnSave": {
 8         "source.fixAll.eslint": true
 9     },
10     //  #让prettier使用eslint的代码格式进行校验
11     // vscode 更新后已经统一使用editor.codeActionsOnsave
12     //  #去掉代码结尾的分号
13     "prettier.semi": false,
14     //  #使用带引号替代双引号
15     "prettier.singleQuote": true,
16     "prettier.tabWidth": 4,
17     //  #让函数(名)和后面的括号之间加个空格
18     "javascript.format.insertSpaceBeforeFunctionParenthesis": true,
19     // #这个按用户自身习惯选择
20     "vetur.format.defaultFormatter.html": "js-beautify-html",
21     // #让vue中的js按"prettier"格式进行格式化
22     "vetur.format.defaultFormatter.js": "prettier",
23     "vetur.format.defaultFormatterOptions": {
24         "js-beautify-html": {
25             // #vue组件中html代码格式化样式
26             "wrap_attributes": "auto",
27             "wrap_line_length": 300,
28             "end_with_newline": false,
29             "semi": false,
30             "singleQuote": true
31         },
32         "prettier": {
33             "semi": false,
34             "singleQuote": true
35         }
36     },
37     "[jsonc]": {
38         "editor.defaultFormatter": "esbenp.prettier-vscode"
39     },
40     // 格式化stylus, 需安装Manta's Stylus Supremacy插件
41     "stylusSupremacy.insertColons": false, // 是否插入冒号
42     "stylusSupremacy.insertSemicolons": false, // 是否插入分号
43     "stylusSupremacy.insertBraces": false, // 是否插入大括号
44     "stylusSupremacy.insertNewLineAroundImports": false, // import之后是否换行
45     "stylusSupremacy.insertNewLineAroundBlocks": false,
46     "prettier.useTabs": true,
47     "files.autoSave": "off",
48     "explorer.confirmDelete": false,
49     "[javascript]": {
50         "editor.defaultFormatter": "esbenp.prettier-vscode"
51     },
52     "[json]": {
53         "editor.defaultFormatter": "esbenp.prettier-vscode"
54     },
55     "diffEditor.ignoreTrimWhitespace": false,
56     "[html]": {
57         "editor.defaultFormatter": "esbenp.prettier-vscode"
58     },
59     "[vue]": {
60         "editor.defaultFormatter": "octref.vetur"
61     }, // 两个选择器中是否换行
62     "eslint.options": {
63         "plugins": [
64             "html"
65         ]
66     },
67     // 添加 vue 支持
68     "eslint.validate": [
69         "javascript",
70         "javascriptreact",
71         "html",
72         "vue"
73     ],
74     "workbench.iconTheme": "vscode-icons",//需要安装插件vscode-icons
75 }

 

 

 

posted @ 2021-12-22 10:47  浅巷深念  阅读(3944)  评论(0编辑  收藏  举报