vscode + eslint + prettier 配置

目标:

  1. 能使用快捷键 alt + ctrl + f进行格式化(html, css, js,vue文件)
  2. 保证 eslint 规则与 vscode 格式化规则一致
  3. 能够自动 import 包,自动删除未使用的多余 import 语句

使用 vscode 格式化时很头疼,因为我安装了prettier插件和eslint插件, 他们都有格式化js文件的功能。

prettier 和 eslint 的规则总是撞车, 刚保存文件自动格式化,立刻又自动执行按照另一种规则给格式化了。

好好研究了一番,发现代码格式化的规范不用那么复杂,因为目前网上流行的配置是 vue-element-admin 项目中那一套配置,几年过去,已经没必要那么复杂

文章尾部有 .prettierrc 配置文件 和 eslint.js 配置,可以直接 copy 到项目中使用

所以,快捷键alt + ctrl + f到底干了什么?

  • vscode 的一旦安装了 prettier 插件,那么此扩展 prettier-vscode 会生成一份默认的格式化配置,如果你本地项目有 .prettierrc 文件,那么就按照你的项目配置文件执行格式化,但不会从 ESLint 配置文件读取配置
  • 而 prettier 和 eslint 的优先级,取决于setting.json中的此项配置
"[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }

当两者混用时(同时安装了 eslint 和 prettier 插件),使用 alt + ctrl + f 进行格式化时,那么就在eslint配置文件 .eslintrc.js中添加上这一句

rules:{
  "prettier/prettier": ["error", {"singleQuote": true, "parser": "flow"}],
}

关于Vue文件中 <script> 和 <style> 中的初次缩进问题

vscode 中的的默认规则是缩进这两部分其中的内容,原因来自于开发者投票,说实话我很不认可这投票,不过为了迎合 vscode 的规范,不得不妥协我的规范。

缩进的 .eslintrc.js配置如下(文档在这)

module.exports = {
  ...
  extends: ['plugin:vue/essential', 'eslint:recommended', '@vue/prettier'],
  ...
  rules: {
    indent: 'off',
    'vue/script-indent': [
      'error',
      2,
      {
        baseIndent: 1,
        switchCase: 1,
        ignores: []
      }
    ],
  }
}

以下是 <script> 和 <style> 标签缩进与未缩进的example 对比

缩进 :

<script>
  import { defineComponent, computed } from 'vue';
  import { useStore } from 'vuex';
  export default defineComponent({
    name: 'App',
    setup() {
      const store = useStore();
      const greyMode = computed(() => store.state.app.greyMode);
      return {
        greyMode
      };
    }
  });
</script>

<style>
  .size {
    min-width: $minWidth;
    width: 100%;
    height: 100%;
  }
</style>

不缩进

<script>
import { defineComponent, computed } from 'vue';
import { useStore } from 'vuex';
export default defineComponent({
  name: 'App',
  setup() {
    const store = useStore();
    const greyMode = computed(() => store.state.app.greyMode);
    return {
      greyMode
    };
  }
});
</script>

<style>
.size {
  min-width: $minWidth;
  width: 100%;
  height: 100%;
}
</style>

1. .prettierrc 配置文件

  • 使用这种格式的配置文件 .prettierrc ,vscode 有配置项提示 (✔)
  • 不使用 js 格式配置文件, 例如 .prettierrc.js (×)

Tips: .prettierrc 这种类型文件其实就是 json 格式

{
  "useTabs": false,
  "tabWidth": 2,
  "endOfLine": "auto",
  "printWidth": 80,
  "semi": true,
  "singleQuote": true,
  "quoteProps": "as-needed",
  "proseWrap": "preserve",
  "arrowParens": "always",
  "bracketSpacing": true,
  "htmlWhitespaceSensitivity": "ignore",
  "ignorePath": ".prettierignore",
  "jsxBracketSameLine": false,
  "jsxSingleQuote": false,
  "requireConfig": false,
  "trailingComma": "none",
  "vueIndentScriptAndStyle": true
}

2. eslint.js 配置文件

细心的同学发现了 , 不是说 json 格式有智能提示吗?

eslint 配置文件为什么用 js 文件格式, 不用json?

这是因为, 我需要根据当前是 development 环境还是 production 环境去做校验.

比如 dev 环境允许 console.log()代码的存在,prod 环境不允许,dev 环境不执行代码压缩,prod 环境执行代码压缩…

接下来的示例中就用到了 变量 process.env.NODE_ENV,而这种变量在json文件中是不允许的.

正是因为 js 文件中含有变数,编辑器(vscode)是不可能知道里面会有什么东西,所以无法给出提示。

// "off"或 0 - 关闭规则
// "warn"或 1 - 开启规则, 使用警告级别的错误: warn(不会导致程序退出)
// "error"或 2 - 开启规则, 使用错误级别的错误: error(当被触发的时候, 程序会退出)
module.exports = {
  root: true,
  env: {
    browser: true,
    node: true,
    es6: true,
  },
  extends: ['plugin:vue/essential', 'eslint:recommended', '@vue/prettier'],
  parserOptions: {
    parser: 'babel-eslint',
    sourceType: 'module',
  },
  // 自定义rules
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'prettier/prettier': ['error', { singleQuote: true, parser: 'flow' }],
    'vue/no-unused-components': 'off',
    'vue/no-unused-vars': 'off',
    'vue/no-multiple-template-root': 'off',
    'vue/max-attributes-per-line': [
      2,
      {
        singleline: 10,
        multiline: {
          max: 2,
          allowFirstLine: false,
        },
      },
    ],
    'vue/singleline-html-element-content-newline': 'off',
    'vue/multiline-html-element-content-newline': 'off',
    'vue/html-closing-bracket-newline': 'off',
    'vue/name-property-casing': ['error', 'PascalCase'],
    'vue/no-v-for-template-key-on-child': 'off',
    indent: 'off',
    'vue/script-indent': [
      'error',
      2,
      {
        baseIndent: 1,
        switchCase: 1,
        ignores: [],
      },
    ],
    'comma-dangle': 'off',
    quotes: [
      'error',
      'single',
      {
        avoidEscape: true,
        allowTemplateLiterals: true,
      },
    ],
    semi: ['error', 'always'],
    'semi-spacing': [
      'error',
      {
        before: false,
        after: true,
      },
    ],
  },
}

其他可能遇到的问题

  1. cant't find module eslint-plugin-vue 解决办法:降低 "eslint-plugin-vue": "^5.2.3", 版本
  2. delete ⏎ prettier/prettier 解决办法:添加配置rules:{'prettier/prettier': ['error', { endOfLine: 'auto' }]}