vite + vue3 + vscode 使用 eslint自动格式化代码

1,895 阅读1分钟

创建项目

npm init vite

创建完成后安装eslint

pnpm i eslint -D

初始化eslint

npx eslint --init

选择一系列配置,这里标准选择的standard

修改.eslintrc.js

module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true
  },
  extends: [
    'plugin:vue/vue3-recommended',
    'standard'
  ],
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module'
  },
  plugins: [
    'vue'
  ],
  rules: {
    semi: [2, 'never'], // 禁止尾部使用分号“ ; ”
    'no-var': 'error', // 禁止使用 var
    indent: ['error', 2], // 缩进2格
    'no-mixed-spaces-and-tabs': 'error', // 不能空格与tab混用
    quotes: [2, 'single'], // 使用单引号
    'vue/html-closing-bracket-newline': 'off', // 不强制换行
    'vue/singleline-html-element-content-newline': 'off', // 不强制换行
    'vue/max-attributes-per-line': ['error', {
      singleline: { max: 5 },
      multiline: { max: 5 }
    }] // vue template模板元素第一行最多5个属性
    // 其它的规则可以去eslint查看,根据自己需要进行添加
  }
}

vscode 安装 eslint 插件,添加配置

    "editor.codeActionsOnSave": {
      "source.fixAll": false,
      "source.fixAll.eslint": true, // this allows ESLint to auto fix on save
      "source.organizeImports": false
    },

现在就可以自动按照eslint来个格式化代码啦。