前端统一代码格式化步骤

178 阅读1分钟

团队里互相配合的时候,统一代码格式这件事必须要做,下面基于 vscode 来记录一下全过程,如有遗漏大家补充。

1. 安装vetur/eslint/stylelint插件

2. settings.json

{
    "editor.formatOnSave": true, // 保存时格式化
    "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true, // 保存时执行eslint修复
        "source.fixAll.stylelint": true // 保存时执行stylelint修复
    },
    "vetur.format.defaultFormatter.js": "prettier-eslint", // 使用eslint修复vue文件的script部分
    "eslint.alwaysShowStatus": true, // 右下角展示ESLint状态,方便查看,可以没有。
    "eslint.validate": [ // 让eslint对javascript和vue执行校验
        "javascript",
        "vue"
    ],
    "vetur.format.defaultFormatter.html": "none", // 关闭vetur对vue中template的格式化,不关会导致prettier格式化生效,进而导致冲突
    "javascript.format.enable": false, // 禁用默认javascript格式化程序,以使eslint有效,不关会冲突
    "vetur.format.options.useTabs": false, // 禁用vetur 的tab缩进
    "stylelint.validate": ["css", "scss", "less"] // 使用stylelint较验指定格式的文件
}

3. 安装如下devDependencies

{
    "babel-eslint": "^10.1.0",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^6.2.2",
    "stylelint": "^14.5.0",
    "stylelint-config-standard": "^25.0.0",
}

4. 根目录下放一个.eslintrc.js,具体规则可以改。

module.exports = {
  root: true,
  env: {
    node: true,
  },
  extends: [
    "eslint:recommended",
    'plugin:vue/recommended',
  ],
  parserOptions: {
    parser: 'babel-eslint',
  },
  plugins: [
    "vue"
  ],
  rules: {
    'no-console': 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    "indent": ["error", 4],
    semi: ["error", "never"],
    "vue/max-attributes-per-line": ["error", {
      "singleline": {
        "max": 1
      },
      "multiline": {
        "max": 1
      }
    }]
  },
}

5. 根目录下放一个.stylelintrc.json,具体规则可以改。

{
    "extends": [
        "stylelint-config-standard"
    ]
}

6. 打开工程的方式

如果settings.json文件中的内容是放在workspace级别的(.vscode/settings.json),VSCode 有工作区的概念,如下图。不要使用这种方式打开,否则读不到settings.json文件中的部分配置。

image-20211215134414123.png