vscode 代码格式,并设置保存时自动格式化代码

本文详细介绍了如何在VSCode中安装和配置插件,如ESLint、Prettier和Vetur,以实现统一的代码格式并在保存时自动执行格式化和ESLint检查,同时提供了.eslintrc.js配置示例和常见错误解决方案。

一、vscode 统一代码格式,并设置保存时自动格式化代码

1、安装插件

1.ESLint
2.Prettier - Code formatter
3.Vetur

2、设置

文件->首选项->设置,点击右上角的箭头所指的按钮(如下图)
在这里插入图片描述在这里插入图片描述
将下面的代码复制粘贴替换,并保存

{
  // vscode默认启用了根据文件类型自动设置tabsize的选项
  "editor.detectIndentation": false,
  // 重新设定tabsize
  "editor.tabSize": 2,
  // 每次保存的时候自动格式化
  "editor.formatOnSave": true,
  "editor.formatOnType": true,
  // 添加 vue 支持
  "eslint.validate": [
    "vue",
    "html",
    "javascript",
    "typescript",
    "javascriptreact",
    "typescriptreact"
  ],
  // 让prettier使用eslint的代码格式进行校验
  "prettier.eslintIntegration": true,
  // 去掉代码结尾的分号
  "prettier.semi": false,
  // 使用单引号替代双引号
  "prettier.singleQuote": true,
  // 让函数(名)和后面的括号之间加个空格
  "javascript.format.insertSpaceBeforeFunctionParenthesis": false,
  // 这个按用户自身习惯选择
  "vetur.format.defaultFormatter.html": "js-beautify-html",
  // 让vue中的js按编辑器自带的ts格式进行格式化
  "vetur.format.defaultFormatter.js": "vscode-typescript",
  "vetur.format.defaultFormatterOptions": {
    "js-beautify-html": {
      "wrap_line_length": 120,
      "wrap_attributes": "auto"
    }
  },
  // 格式化stylus, 需安装Manta's Stylus Supremacy插件
  "stylusSupremacy.insertColons": false, // 是否插入冒号
  "stylusSupremacy.insertSemicolons": false, // 是否插入分号
  "stylusSupremacy.insertBraces": false, // 是否插入大括号
  "stylusSupremacy.insertNewLineAroundImports": false, // import之后是否换行
  "stylusSupremacy.insertNewLineAroundBlocks": false,
  "explorer.confirmDelete": false,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "eslint.nodePath": "",
  "diffEditor.ignoreTrimWhitespace": false,
  "[javascript]": {
    "editor.defaultFormatter": "vscode.typescript-language-features"
  },
  "[typescriptreact]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[javascriptreact]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[jsonc]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "editor.fontSize": 12,
  "update.showReleaseNotes": false,
  "update.mode": "none",
  "workbench.startupEditor": "none"
}

重新打开vscode,在保存的时候,自动根据ES规则检查并修改语法
PS: 格式化快捷键为【Shift】+【Alt】+ F

3、可根据实际情况,调整ESLint 校验规则

在这里插入图片描述

附上我本地的.eslintrc.js供参考,配置如下:

// ESlint 检查配置
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
    }],
    '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']
  }
}

二、ESLint 检查保存,问题汇总
1、报错提示:Binding “columns” should be on a new line.eslint(vue/max-attributes-per-line)
此问题是由于.eslintrc.js文件中的vue/max-attributes-per-line配置错误产生的
解决方法:改为警告,rules添加或修改

'vue/max-attributes-per-line': ['2', {
  'singleline': 10,
  'multiline': {
    'max': 1,
    'allowFirstLine': false
  }
}],
2、报错提示:Expected indentation of 15 spaces but found 8 spaces.eslint(vue/html-indent)

解决方法:修改eslint配置文件.eslintrc.js,rules添加或修改

'vue/html-indent': ['2', 2, {
  'attribute': 1,
  'baseIndent': 1,
  'closeBracket': 0,
  'alignAttributesVertically': true,
  'ignores': []
}],

3、报错提示:Missing space before function parentheses.eslint(space-before-function-paren)
原因:使用eslint时,严格模式下,方法名和括号之间需要有一个空格
解决方法:在eslintrc文件中找到rules节点,配置 ‘space-before-function-paren’: 0

<think>我们正在处理用户关于在VSCode中配置保存时自动格式化代码的问题。用户已经提供了一些引用,但我们需要根据这些引用和之前的知识来回答。 关键点: 1. 用户希望实现保存时自动格式化代码。 2. 引用[1]提到了使用ESLint+Prettier,配置保存时自动格式化和修复。 3. 引用[3]给出了一个配置:在settings.json中添加"editor.codeActionsOnSave": { "source.fixAll.eslint": true },这用于ESLint的自动修复。 4. 引用[2]是关于配置bash和git以及设置扩展目录的,与当前问题关系不大。 5. 引用[4]是关于C/C++配置文件的格式说明,与当前问题关系不大。 因此,我们可以提供两种主要方法: 方法1:使用Prettier(如之前回答的) 方法2:使用ESLint(如果项目已经配置了ESLint) 我们将结合引用[1]和引用[3]来提供ESLint的配置方法。 步骤: 1. 安装必要的扩展:Prettier和ESLint。 2. 配置保存时自动格式化,可以选择使用Prettier作为格式化工具,或者使用ESLint来修复问题。 3. 如果需要,可以配置Prettier和ESLint的规则,避免冲突。 注意:用户可能使用不同的语言或工具,因此我们提供通用的方法,说明如何针对不同情况调整。 我们将按照以下结构回答: - 方法一:使用Prettier(通用格式化工具) - 方法二:使用ESLint(适用于JavaScript/TypeScript等项目) - 可选配置:解决Prettier和ESLint的冲突 - 测试验证 - 常见问题 最后,生成相关问题。 注意:用户之前的问题和我们的回答已经详细说明了Prettier的配置,所以这里可以简要提一下,重点补充ESLint的方法。</think>### VSCode 保存时自动格式化代码配置指南 通过以下配置可实现保存文件时自动格式化代码(支持 JavaScript/TypeScript/Python/HTML/CSS 等主流语言),**无需手动触发**。根据需求选择方案: --- #### ✅ 方案一:使用 Prettier(通用格式化工具) **适用场景**:多语言统一风格、简单配置 1. **安装扩展** - 扩展市场搜索安装 [Prettier - Code formatter](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) 2. **开启保存时格式化** - 打开设置 (`Ctrl+,`) → 搜索 `format on save` → 勾选 **`Editor: Format On Save`** ![开启保存格式化](https://i.imgur.com/5fG3t7g.png) 3. **设置默认格式化器** - 搜索 `default formatter` → 选择 **`esbenp.prettier-vscode`** 4. **自定义规则**(可选) 在项目根目录创建 `.prettierrc`: ```json { "semi": true, // 强制分号 "singleQuote": true, // 使用单引号 "tabWidth": 2 // 缩进2空格 } ``` --- #### ✅ 方案二:使用 ESLint(JS/TS 项目专用) **适用场景**:需同时进行代码质量检查和格式化的 JS/TS 项目 1. **前置条件** - 安装 [ESLint 扩展](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) - 项目已配置 ESLint(含 `eslint-plugin-prettier`) 2. **关键配置** 在 `.vscode/settings.json` 添加: ```json { "editor.codeActionsOnSave": { "source.fixAll.eslint": true // 保存时触发ESLint自动修复 }, "eslint.format.enable": true // 允许ESLint处理格式化 } ``` > 此配置会调用 ESLint 的 `--fix` 能力自动修复代码风格问题[^1][^3] --- #### 🛠 混合方案:ESLint + Prettier 协作 **解决规则冲突**:当 ESLint 与 Prettier 规则不一致时 1. 安装依赖: ```bash npm install eslint-config-prettier eslint-plugin-prettier --save-dev ``` 2. 在 ESLint 配置 (`.eslintrc.js`) 中扩展 Prettier: ```js module.exports = { extends: [ 'eslint:recommended', 'plugin:prettier/recommended' // 将Prettier规则作为ESLint规则应用 ] } ``` 3. VS Code 配置(`.vscode/settings.json`): ```json { "editor.defaultFormatter": "esbenp.prettier-vscode", "editor.formatOnSave": true, "editor.codeActionsOnSave": { "source.fixAll.eslint": true } } ``` > 此时 Prettier 负责格式化,ESLint 负责质量检查,规则通过 `eslint-config-prettier` 避免冲突[^1] --- #### 🔍 验证与调试 1. **测试文件**:创建 `test.js` 输入未格式化代码: ```js const test={name:'demo'};function foo(){console.log('unformatted')} ``` 2. 保存文件 (`Ctrl+S`) → 观察自动格式化效果: ```js const test = { name: "demo" }; function foo() { console.log("formatted"); } ``` 3. **状态栏检查**: - 右下角确认已激活 `Prettier` 或 `ESLint` - 点击状态栏切换格式化工具 --- #### ⚠️ 常见问题解决 | 问题 | 解决方案 | |-----------------------|--------------------------------------------------------------------------| | 保存后无变化 | 1. 检查扩展是否激活<br>2. 在代码文件右键 → `格式化文档` → 手动选择工具 | | ESLint 不生效 | 1. 确认项目有 `eslint` 依赖<br>2. 检查 `.eslintrc` 配置是否正确 | | 语言不支持 | Python 需安装 [Python 扩展](https://marketplace.visualstudio.com/items?itemName=ms-python.python) + `autopep8` | | 团队配置同步 | 将 `.vscode/settings.json` 和 `.prettierrc` 提交到 Git 仓库 | > 通过 `Ctrl+Shift+P` → `Preferences: Open Settings (JSON)` 可直接编辑全局配置[^2]。 --- ### 相关问题 1. 如何为 Python 配置保存时自动格式化(如 `black` 或 `autopep8`)? 2. ESLint 和 Prettier 规则冲突时如何优先使用某种规则? 3. 如何在不同项目中自动切换格式化配置? 4. 保存时自动格式化与手动快捷键 (`Shift+Alt+F`) 性能有何差异? 5. 如何通过 VS Code 插件实现 Git 提交前的自动格式化? > 配置完成后,VS Code 会在每次保存时自动调用格式化工具,确保代码风格统一[^1][^3]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值