Vue学习笔记7 - 在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文件中,增加一项

//settings.json
{
    .....

    "editor.formatOnSave": true, // 在保存时自动格式化
    "vetur.format.options.tabSize": 4,
}

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

// settings.json
{
  ....
  "vetur.format.styleInitialIndent": true,
  "vetur.format.scriptInitialIndent": true,

}

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

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

// settings.json

{
  ......

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

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

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

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

但是实际测试下来,.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 有冲突。不过我们先用来说明一下,还是问题不大了。

// .eslintrc.js
module.exports = {
    "env": {
        "browser": true,
        "es2021": true,    // 还是改为"es6": true
        "node": true
    },
    "extends": [
        "eslint:recommended",
        "plugin:vue/essential"
    ],
    "parserOptions": {
        "ecmaVersion": 12,
        "sourceType": "module"
    },
    "plugins": [
        "vue"
    ],
    "rules": {
    }
};

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

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

由于我们选择的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的相关配置。

// settings.json
{
.......

  // 指定eslint校验的文件类型
  "eslint.validate": [
    "javascript",
    "javascriptreact",
    "html",
    "vue"
  ],
  // "eslint.autoFixOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "eslint.run": "onSave",   // 保存就校验
}

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

//package.json
{
  ......

  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },

  ......
}

这样,在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如下:

// .eslintrc.js
module.exports = {
    "root": true,    // 表明这就是根目录了,停止去父级目录中寻找配置
    "env": {    //用来预定义全局环境变量,常用的有browser,es6,node,jest,jquery
        "browser": true,
        "es6": true,
        "node": true
    },
    "parserOptions": {  // 支持的 JavaScript 语言选项
        "parser": "babel-eslint",   // 默认使用Espree作为其解析器,除此之外就Esprima,Babel-ESLint,@typescript-eslint/parser
        "ecmaVersion": 12, // ECMAScript 版本,默认设置为 3,5(默认),也可以年份,2015(同 6),2012(as 12)
        "sourceType": "module"  // "script" (默认) 或 "module"(如果你的代码是 ECMAScript 模块)
    },
    "extends": [    // 规则模版
        "eslint:recommended",   // 启用一系列核心规则,
        "plugin:vue/essential",  // 启用eslint vue插件的规则模版,base,essential,strongly-recommended,recommended(最严)
    ],
    "plugins": [    //eslint支持使用第三方插件,需要npm先安装,后使用
        "vue",   // 可以用package的名称,eslint-plugin-vue,也可以省略eslint-plugin-,直接填写vue
    ],
    "rules": {  //补充规则
        // 强制使用单引号
        'quotes': ['error', 'single'],
        // 在块级作用域外访问块内定义的变量是否报错提示
        'block-scoped-var': 0,
        "vue/max-attributes-per-line": 0,
        "vue/singleline-html-element-content-newline": "off",
        "vue/multiline-html-element-content-newline": "off",
        "vue/name-property-casing": ["error", "PascalCase"],
        "vue/no-v-html": "off",
        'accessor-pairs': 2,
        'arrow-spacing': [2, {
            'before': true,
            'after': true
        }],
        'block-spacing': [2, 'always'],
        'brace-style': [2, '1tbs', {
            'allowSingleLine': true
        }],
        'camelcase': [0, {
            'properties': 'always'
        }],
        'comma-dangle': 0,
        'comma-spacing': [2, {
            'before': false,
            'after': true
        }],
        'comma-style': [2, 'last'],
        'constructor-super': 2,
        'curly': [2, 'multi-line'],
        'dot-location': [2, 'property'],
        'eol-last': 2,
        'eqeqeq': ["error", "always", { "null": "ignore" }],
        'generator-star-spacing': [2, {
            'before': true,
            'after': true
        }],
        'handle-callback-err': [2, '^(err|error)$'],
        'indent': [2, 4, {
            'SwitchCase': 1
        }],
        'jsx-quotes': [2, 'prefer-single'],
        'key-spacing': [2, {
            'beforeColon': false,
            'afterColon': true
        }],
        'keyword-spacing': [2, {
            'before': true,
            'after': true
        }],
        'new-cap': [2, {
            'newIsCap': true,
            'capIsNew': false
        }],
        'new-parens': 2,
        'no-array-constructor': 2,
        'no-caller': 2,
        'no-console': 'off',
        'no-class-assign': 2,
        'no-cond-assign': 2,
        'no-const-assign': 2,
        'no-control-regex': 0,
        'no-delete-var': 2,
        'no-dupe-args': 2,
        'no-dupe-class-members': 2,
        'no-dupe-keys': 2,
        'no-duplicate-case': 2,
        'no-empty-character-class': 2,
        'no-empty-pattern': 2,
        'no-eval': 2,
        'no-ex-assign': 2,
        'no-extend-native': 2,
        'no-extra-bind': 2,
        'no-extra-boolean-cast': 2,
        'no-extra-parens': [2, 'functions'],
        'no-fallthrough': 2,
        'no-floating-decimal': 2,
        'no-func-assign': 2,
        'no-implied-eval': 2,
        'no-inner-declarations': [2, 'functions'],
        'no-invalid-regexp': 2,
        'no-irregular-whitespace': 2,
        'no-iterator': 2,
        'no-label-var': 2,
        'no-labels': [2, {
            'allowLoop': false,
            'allowSwitch': false
        }],
        '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-negated-in-lhs': 2,
        'no-new-object': 2,
        'no-new-require': 2,
        'no-new-symbol': 2,
        'no-new-wrappers': 2,
        'no-obj-calls': 2,
        'no-octal': 2,
        'no-octal-escape': 2,
        'no-path-concat': 2,
        'no-proto': 2,
        'no-redeclare': 2,
        'no-regex-spaces': 2,
        'no-return-assign': [2, 'except-parens'],
        'no-self-assign': 2,
        'no-self-compare': 2,
        'no-sequences': 2,
        'no-shadow-restricted-names': 2,
        'no-spaced-func': 2,
        'no-sparse-arrays': 2,
        'no-this-before-super': 2,
        'no-throw-literal': 2,
        'no-trailing-spaces': 2,
        'no-undef': 2,
        'no-undef-init': 2,
        'no-unexpected-multiline': 2,
        'no-unmodified-loop-condition': 2,
        'no-unneeded-ternary': [2, {
            'defaultAssignment': false
        }],
        'no-unreachable': 2,
        'no-unsafe-finally': 2,
        'no-unused-vars': [2, {
            'vars': 'all',
            'args': 'none'
        }],
        'no-useless-call': 2,
        'no-useless-computed-key': 2,
        'no-useless-constructor': 2,
        'no-useless-escape': 0,
        'no-whitespace-before-property': 2,
        'no-with': 2,
        'one-var': [2, {
            'initialized': 'never'
        }],
        'operator-linebreak': [2, 'after', {
            'overrides': {
                '?': 'before',
                ':': 'before'
            }
        }],
        'padded-blocks': [2, 'never'],
        'quotes': [2, 'single', {
            'avoidEscape': true,
            'allowTemplateLiterals': true
        }],
        '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
        }],
        'spaced-comment': [2, 'always', {
            'markers': ['global', 'globals', 'eslint', 'eslint-disable', '*package', '!', ',']
        }],
        'template-curly-spacing': [2, 'never'],
        'use-isnan': 2,
        'valid-typeof': 2,
        'wrap-iife': [2, 'any'],
        'yield-star-spacing': [2, 'both'],
        'yoda': [2, 'never'],
        'prefer-const': 2,
        'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
        'object-curly-spacing': [2, 'always', {
            objectsInObjects: false
        }],
        'array-bracket-spacing': [2, 'never']
    }
};

然后,就发现有不少冲突了,先暂时不管,我们来进行下一步,用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文件

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

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

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

上面两项配置可以简化成

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

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

//.eslintrc.js
module.exports = {
    "root": true, 
    // .....  

    "extends": [    // 规则模版
        "eslint:recommended",   // 启用一系列核心规则,
        "plugin:vue/essential",  // 启用eslint vue插件的规则模版,base,essential,strongly-recommended,recommended(最严)
        "plugin:prettier/recommended"    // prettier新增
    ],
    "plugins": [    //eslint支持使用第三方插件,需要npm先安装,后使用
        "vue",   // 可以用package的名称,eslint-plugin-vue,也可以省略eslint-plugin-,直接填写vue
        "prettier" // prettier新增
    ],
    // .....

}

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

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

这样基本可以说,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如下

// settings.json
{
    "workbench.startupEditor": "newUntitledFile",
    "files.autoSave": "off",    // 关闭文件自动保存,避免开发时候页面变化
    "editor.tabSize": 4, // tab距离
    "editor.formatOnSave": true, // 在保存时自动格式化
    "editor.minimap.enabled": false, // 关闭右侧快速预览
    "files.eol": "\n", // 设定文件的换行符,\n(linux模式)或\r\n(win模式)
    "editor.detectIndentation": false, // 关闭vscode的缩进检查
    "editor.fontSize": 14, //设置文字大小
    "editor.lineHeight": 0, //设置文字行高
    "editor.lineNumbers": "on", //开启行数提示
    "editor.quickSuggestions": {
        //开启自动显示建议
        "other": true,
        "comments": true,
        "strings": true
    },
    "window.zoomLevel": 0, // 调整窗口的缩放级别
    //根据文件后缀名定义vue文件类型
    "files.associations": {
        "*.vue": "vue"
    },
    // 为各类文件制定Fatmatter插件
    "[vue]": {
        // "editor.defaultFormatter": "esbenp.prettier-vscode"  // 采用prettier处理格式化
        "editor.defaultFormatter": "octref.vetur" // 采用vetur来处理Fatmatter
    },
    "[javascript]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[json]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[jsonc]": {
        "editor.defaultFormatter": "vscode.json-language-features"
    },
    // Vetur 的各类设定,仅当上面[vue]的editor.defaultFormatter的值为octref.vetur的时候,才起效
    "vetur.format.options.tabSize": 4,
    "vetur.format.styleInitialIndent": false, // 关闭vue中script标签初始缩进,开启会和eslint的缩进校验冲突
    "vetur.format.scriptInitialIndent": false, // 关闭vue中style标签初始缩进,开启会和eslint的缩进校验冲突
    "vetur.format.defaultFormatter.html": "js-beautify-html", // 针对vue中的template部分的风格模版,也可以是:prettier
    "vetur.format.defaultFormatter.js": "prettier-eslint", // 针对vue中的script部分的风格模版,或者prettier
    "vetur.format.defaultFormatter.css": "prettier", // 针对vue中的style部分的风格模版
    "vetur.format.defaultFormatterOptions": {
        "js-beautify-html": { // 配置不能和prettier的配置冲突,eslint校验的时候采用的prettier的风格
            // 给js-beautify-html设置属性隔断
            "wrap_line_length": 220, //换行长度
            // 属性换行
            // 对属性进行换行。
            // - auto: 仅在超出行长度时才对属性进行换行。
            // - force: 对除第一个属性外的其他每个属性进行换行。
            // - force-aligned: 对除第一个属性外的其他每个属性进行换行,并保持对齐。
            // - force-expand-multiline: 对每个属性进行换行。
            // - aligned-multiple: 当超出折行长度时,将属性进行垂直对齐。
            "wrap_attributes": "auto",
            // Maximum number of line breaks to be preserved in one chunk (0 disables)
            // "max_preserve_newlines": 0,
            "end_with_newline": false
        },
        "prettyhtml": {
            "printWidth": 220,
            "singleQuote": false,
            "wrapAttributes": false,
            "sortAttributes": false
        }
        // "prettier": {
        //         // Prettier option here
        //         "printWidth": 120,
        //         "trailingComma": "none", // 多行时,尽可能打印尾随的逗号
        //         "tabWidth": 4, // 会忽略vetur的tabSize配置
        //         "useTabs": false, // 是否利用tab替代空格
        //         "semi": false, // 句尾是否加;
        //         "singleQuote": true, // 使用单引号而不是双引号
        //         "arrowParens": "avoid", // allow paren-less arrow functions 箭头函数的参数使用圆括号
        // }
    },
    // ESLint 的相关配置
    "eslint.validate": [
        "javascript",
        "javascriptreact",
        "vue"
    ], // eslint校验的文件类型
    // 该属性相当于配置js文件的操作
    // "[javascript]": {
    //   "editor.formatOnSave": true,
    //   "editor.defaultFormatter": "esbenp.prettier-vscode"
    // },
    // "eslint.autoFixOnSave": true,  很多插件提示这么设定,但实际vscode中已经弃用这个设置,改用下面的方式。
    "editor.codeActionsOnSave": {
        // 保存时触发的事件
        "source.fixAll.eslint": true // 自动fix eslint
    },
    "eslint.run": "onSave", // 保存就校验
    // 函数名后增加空格
    "javascript.format.insertSpaceBeforeFunctionParenthesis": true,
    "javascript.format.insertSpaceAfterFunctionKeywordForAnonymousFunctions": true,
}

除了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的文件,才解决了换行符的问题。

# https://editorconfig.org
root = true

[*]
charset = utf-8
indent_style = space
indent_size = 4
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
insert_final_newline = false
trim_trailing_whitespace = false

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

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

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

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

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

对规则别人发布的规则配置不满意的,去官网查了自己改。

补充:

之后,为了保证所有项目都可以使用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

  • 25
    点赞
  • 101
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 要配置 Vue-Element-Admin 的 ESLint 为 false,可以按照以下步骤进行操作: 1. 打开项目根目录下的 `.eslintrc.js` 文件; 2. 将 `extends` 属性的 `eslint:recommended` 去掉; 3. 将 `rules` 属性的所有规则改为 `0`,表示关闭 ESLint 检查; 4. 保存文件并重新启动项目。 以下是一个示例的 `.eslintrc.js` 文件内容: ``` module.exports = { root: true, env: { node: true }, rules: { 'no-console': 'off', 'no-debugger': 'off' }, parserOptions: { parser: 'babel-eslint' } } ``` 将 `rules` 属性的规则改为 `0`,即可关闭 ESLint 检查。例如将 `'no-console': 'off'` 改为 `'no-console': 0`。 ### 回答2: 在vue-element-admin项目配置esLint为false可以通过以下步骤完成: 1. 打开vue-element-admin项目根目录,找到根目录下的.eslintrc.js文件。 2. 打开.eslintrc.js文件,可以看到里面有一系列的规则配置。 3. 找到rules属性,该属性下是各种eslint规则的配置。 4. 将rules属性改为`"rules": {}`,即将里面的全部规则配置删除。 5. 保存文件,关闭编辑器。 6. 重新启动项目,此时项目eslint就会被禁用了。 配置esLint为false的目的是为了避免eslint对代码进行代码规范和风格检查。通常情况下,eslint是用来规范团队开发的代码风格和质量的,但在部分情况下,可能并不需要进行代码规范和风格的检查,因此可以将eslint禁用掉。 需要注意的是,禁用eslint会导致代码规范和风格的统一性降低,可能会增加代码质量的隐患,因此在禁用eslint之前,建议对代码进行规范和风格的检查,确保代码的质量。 ### 回答3: 在vue-element-admin,可以通过配置文件来将ESLint的开启状态设置为false。ESLint是用于检查代码规范的工具,开启后会在开发过程实时检查代码是否符合规范。 要配置ESLint为false,需要进行以下步骤: 1. 打开vue-element-admin项目的根目录,在根目录下找到.vue文件。 2. 找到.vue文件vue.config.js配置文件,如果不存在,则需要手动创建。 3. 在vue.config.js文件,新增一个属性lintOnSave,并将其值设置为false,示例代码如下: ``` module.exports = { lintOnSave: false } ``` 4. 保存vue.config.js文件。 5. 重新启动vue-element-admin项目。 通过以上步骤,将ESLint的开启状态设置为false后,项目在开发过程将不再进行实时的代码规范检查。这样可以避免一些普通的规范问题对开发效率的影响。但是需要注意的是,禁用ESLint可能导致一些潜在的问题未被发现,因此在正式发布项目之前,建议开启ESLint并仔细检查代码规范。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值