vscode如何安装eslint插件 代码自动修复

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

方法和步骤:

通常情况下vue项目都会添加eslint组件,我们可以查看webpack的配置文件package.json查看,也可以查看工程下是否有.eslintrc.js和.eslintignore查看到eslint是否开启。

 

 当我们编写不符合eslint规范的代码时,启动项目会报错,比如

这个时候可以安装vscode eslint插件,就可以自动检测不符合规范的代码。打开vscode左侧扩展面板,搜索eslint,点击安装,重启后生效

 安装好之后,还需要在vscode文件中进行设置:

通过  file->preferences->Settings 出现如下界面:

 点击红框,则会出现配置文件

 把以下代码复制到这个文件中:

复制代码
{
  // vscode默认启用了根据文件类型自动设置tabsize的选项
  "editor.detectIndentation": false,
  // 重新设定tabsize
  "editor.tabSize": 2,
  // #每次保存的时候自动格式化
  "editor.formatOnSave": true,
  // #每次保存的时候将代码按eslint格式进行修复
  "eslint.autoFixOnSave": true,
  // 添加 vue 支持
  "eslint.validate": [
    "javascript",
    "javascriptreact",
    {
      "language": "vue",
      "autoFix": true
    }
  ],
  //  #让prettier使用eslint的代码格式进行校验
  "prettier.eslintIntegration": true,
  //  #去掉代码结尾的分号
  "prettier.semi": false,
  //  #使用带引号替代双引号
  "prettier.singleQuote": true,
  //  #让函数(名)和后面的括号之间加个空格
  "javascript.format.insertSpaceBeforeFunctionParenthesis": true,
  // #让vue中的js按编辑器自带的ts格式进行格式化
  "vetur.format.defaultFormatter.js": "vscode-typescript",
  "vetur.format.defaultFormatterOptions": {
    "js-beautify-html": {
      "wrap_attributes": "force-aligned"
      // #vue组件中html代码格式化样式
    }
  },
  "window.zoomLevel": 0,
  "explorer.confirmDelete": false,
  "explorer.confirmDragAndDrop": false,
  "editor.renderControlCharacters": true,
  "editor.renderWhitespace": "all"
}
复制代码

然后在项目的.eslintrc.js中添加如下代码:

复制代码
// https://eslint.org/docs/user-guide/configuring

module.exports = {
  root: true,
  parserOptions: {
    parser: 'babel-eslint'
  },
  env: {
    browser: true
  },
  extends: [
    // https://github.com/vuejs/eslint-plugin-vue#priority-a-essential-error-prevention
    // consider switching to `plugin:vue/strongly-recommended` or `plugin:vue/recommended` for stricter rules.
    'plugin:vue/essential',
    // https://github.com/standard/standard/blob/master/docs/RULES-en.md
    'standard'
  ],
  // required to lint *.vue files
  plugins: ['vue'],
  // add your custom rules here
  rules: {
    // allow async-await
    'no-console': 'off',
    indent: ['error', 2, { SwitchCase: 1 }],
    semi: ['error', 'always'],
    'space-before-function-paren': [
      'error',
      { anonymous: 'always', named: 'never' }
    ],
    'generator-star-spacing': 'off',
    // allow debugger during development
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
  }
}
复制代码

ctrl + s保存代码后,便会自动修复格式不正确的代码

猜你喜欢

转载自www.cnblogs.com/ranyonsue/p/12704680.html