VsCode中关于Vue项目代码格式化和eslint规范的配置
一、安装插件
Vetur:针对于vue设计的插件,具有代码高亮、代码片段、代码格式化等功能
ESLint:主要用来检测代码的语法格式,以便我们规范书写,避免因编译所发生的错误
Prettier - Code formatter:该插件主要用于格式化代码
二、配置
vscode 左下角设置-用户-右上角打开设置 (json) - settings.json
或者在项目文件夹下的 .vscode/settings.json
中配置(仅在当前项目生效)
// settings.json
{
// 编辑器基本设置
"editor.formatOnSave": true, //保存时格式化
"editor.tabSize": 2, //设置Tab键的空格数
"editor.insertSpaces": true, //控制编辑器在按下 Tab 键时是插入空格还是制表符(Tab 字符)
"editor.renderWhitespace": "boundary", //控制编辑器是否显示以及如何显示空白字符,此处设置渲染空格的方式为边界(小点)
"editor.lineNumbers": "on", //显示行号
"editor.folding": true, //启用代码折叠
// 代码操作配置
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit", //保存文件时自动修复eslint错误
// "source.organizeImports": "explicit",//控制是否在保存时自动整理导入语句(如删除未使用的导入、排序导入等),会产生eslint错误而不修复
}, //配置在保存文件时自动执行哪些代码
// 语言特定格式化器
"[vue]": {
"editor.defaultFormatter": "octref.vetur",
}, //vue文件默认格式化工具为vetur
"[javascript]": {
"editor.defaultFormatter": "vscode.typescript-language-features",
}, //javascript文件默认格式化工具为VSCode内置的TypeScript语言服务扩展
"[json]": {
"editor.defaultFormatter": "vscode.json-language-features",
"editor.formatOnSave": true,
}, //json文件默认格式化工具为VSCode内置的JSON语言服务扩展
"[jsonc]": {
"editor.defaultFormatter": "vscode.json-language-features",
"editor.formatOnSave": true,
}, //jsonc文件默认格式化工具为VSCode内置的JSON语言服务扩展
// ESLint 配置
"eslint.validate": [
"javascript",
"javascriptreact",
"vue",
"html",
"json",
"jsonc"
], //配置ESLint验证的语言类型
"eslint.quiet": true, //控制 ESLint 是否只显示错误而忽略警告
"eslint.workingDirectories": [
{
"mode": "auto"
}
], //配置ESLint会自动检测合适的工作目录
// Vetur 配置
"vetur.ignoreProjectWarning": true, //忽略Vetur项目警告
"vetur.format.defaultFormatter.js": "vscode-typescript", //javascript文件默认格式化工具为VSCode内置的TypeScript语言服务扩展
"vetur.format.defaultFormatter.ts": "vscode-typescript", //typescript文件默认格式化工具为VSCode内置的TypeScript语言服务扩展
"vetur.format.defaultFormatter.html": "js-beautify-html", //html文件默认格式化工具为js-beautify-html
"vetur.format.defaultFormatter.scss": "prettier", //scss文件默认格式化工具为prettier
"vetur.format.scriptInitialIndent": true, //控制vue文件中<script>标签内的代码是否缩进
"vetur.format.styleInitialIndent": true, //控制vue文件中<style>标签内的代码是否缩进
"vetur.validation.template": true, //控制vue文件中<template>标签内的代码是否验证
"vetur.validation.script": true, //控制vue文件中<script>标签内的代码是否验证
"vetur.validation.style": true, //控制vue文件中<style>标签内的代码是否验证
"vetur.format.defaultFormatterOptions": {
"js-beautify-html": {
"wrap_line_length": 80, //控制html文件格式化时的行长
"wrap_attributes": "force-expand-multiline", //控制html文件格式化时的属性换行方式,强制将所有属性放在单独的行上
"end_with_newline": true, //控制html文件格式化时是否在文件末尾添加新行
"indent_char": " ", //控制html文件格式化时的缩进字符,此处设置为空格
"indent_size": 2, //控制html文件格式化时的缩进大小,此处设置为2个空格
}, //配置js-beautify-html格式化选项
},
// Prettier 配置
"prettier.vueIndentScriptAndStyle": true, //控制vue文件中<script>和<style>标签内的代码是否应该相对于<template>标签进行缩进
"prettier.singleQuote": true, //控制是否使用单引号而不是双引号
"prettier.useTabs": false, //控制是否使用制表符(Tab 字符)而不是空格进行缩进
"prettier.printWidth": 100, //当一行代码的长度超过 100 个字符时,Prettier 会尝试在合适的位置进行换行,使代码更易于阅读
"prettier.tabWidth": 2, //控制Prettier格式化时的缩进大小,此处设置为2个空格
"prettier.trailingComma": "es5", //控制Prettier格式化时是否在对象字面量、数组字面量、函数参数列表和调用表达式的尾随逗号,此处设置为ES5规范
"prettier.bracketSpacing": true, //控制Prettier格式化时是否在对象字面量、数组字面量、函数参数列表和调用表达式的括号之间添加空格,此处设置为添加空格
"prettier.semi": true, //控制Prettier格式化时是否在语句末尾添加分号,此处设置为添加分号
"prettier.arrowParens": "always", //控制Prettier格式化时是否在箭头函数参数周围添加括号,此处设置为始终添加括号
// HTML 格式化
"html.format.wrapAttributes": "force-expand-multiline", //控制html文件格式化时的属性换行方式,强制将所有属性放在单独的行上
"html.format.wrapLineLength": 80, //控制html文件格式化时的行长
// JavaScript/TypeScript 配置
"javascript.format.insertSpaceBeforeFunctionParenthesis": true, //控制javascript文件格式化时是否在函数参数列表前添加空格
"javascript.format.insertSpaceAfterConstructor": true, //控制javascript文件格式化时是否在构造函数调用后添加空格
"javascript.preferences.quoteStyle": "single", //控制javascript文件格式化时使用单引号而不是双引号
"typescript.format.insertSpaceAfterConstructor": true, //控制typescript文件格式化时是否在构造函数调用后添加空格
"typescript.format.insertSpaceBeforeFunctionParenthesis": true, //控制typescript文件格式化时是否在函数参数列表前添加空格
"typescript.preferences.quoteStyle": "single", //控制typescript文件格式化时使用单引号而不是双引号
// JSON 特定格式化配置
"json.format.enable": true,
"json.format.keepLines": true,
"json.validate.enable": true,
// Git 配置
"git.ignoreLimitWarning": true, //忽略 Git 仓库中文件数量过多时的警告提示
"git.confirmSync": false, //在执行 Git 同步操作前不显示确认对话框
// 文件配置
// "files.autoSave": "afterDelay",//在文件停止编辑一段时间后自动保存
// "files.autoSaveDelay": 1000,//自动保存延迟时间,此处设置为1000毫秒
// "files.insertFinalNewline": true,//在文件末尾添加新行
// 搜索配置
"search.exclude": {
"**/node_modules": true,
"**/dist": true,
"**/build": true,
"**/.git": true,
"**/.vscode": true,
}, //控制在 VSCode 的全局搜索中需要排除的文件或目录
}
ESLint 的检测规则可以额外配置,支持多种格式的配置文件:
- JavaScript - 使用 .eslintrc.js 并导出包含您的配置的对象。
- JavaScript (ESM) - 在 package.json 中指定 “type”:“module” 的 JavaScript 包中运行 ESLint 时使用 .eslintrc.cjs。请注意,ESLint 目前不支持 ESM 配置。
- YAML - 使用 .eslintrc.yaml 或 .eslintrc.yml 定义配置结构。
- JSON - 使用 .eslintrc.json 定义配置结构。ESLint 的 JSON 文件也允许 JavaScript 样式的注释。
- package.json - 在您的 package.json 文件中创建一个 eslintConfig 属性并在那里定义您的配置。
如果同一目录下有多个配置文件,ESLint 只会使用一个。优先顺序如下:
- .eslintrc.js
- .eslintrc.cjs
- .eslintrc.yaml
- .eslintrc.yml
- .eslintrc.json
- package.json
ESLint v8.23.0 开始,新增扁平化配置文件格式 eslint.config.js
,下面以 .eslintrc.js
为例:
// .eslintrc.js
module.exports = {
root: true,
parserOptions: {
parser: 'babel-eslint',
sourceType: 'module'
},
env: {
browser: true,
node: true,
es6: true,
},
extends: ['plugin:vue/recommended', 'eslint:recommended'],
// add your custom rules here
//it is base on https://github.com/vuejs/eslint-config-vue
rules: {
"vue/max-attributes-per-line": [2, {
"singleline": 10,
"multiline": {
"max": 1,
"allowFirstLine": false
}
}],
"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': [2, 'never'],
'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, 2, {
'SwitchCase': 1
}],
"vue/script-indent": [2, 2, {
"baseIndent": 1,
'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'],//和async箭头函数冲突
'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']
},
overrides: [
{
'files': ['*.vue'],
'rules': {
'indent': 'off'
}
}
],
}
检测规则参考 vue-admin-template 的 .eslintrc.js
文件,新增针对 script 标签首层缩进报错问题的解决办法
rules: {
...
"vue/script-indent": [2, 2, {
"baseIndent": 1,
'switchCase': 1
}],
...
},
overrides: [
{
'files': ['*.vue'],
'rules': {
'indent': 'off'
}
}
],