格式化配置

624 阅读6分钟

简单整理了一些日常用到的格式化配置。

vscode配置

上传vscode编辑配置,可以减少团队其他人编辑器的配置工作。

  1. 新建.vscode文件夹,新建文件settings.json文件。该文件为vscode配置文件,会覆盖vscode配置。vscode的settings文件中可以配置prettier扩展,如prettier.semi:true,需要注意的是如果配置了.prettierrc文件,则.prettierrc的优先级是更高的。
  2. 配置说明
  "editor.formatOnSave": true,// 保存时自动格式化
  "editor.defaltFormatter": "esbenp.prettier-vscode",// 默认使用prettier作为编辑器等格式化插件
  "[vue]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"// 对vue文件使用prettier作为格式化工具
  },
  "[jsonc]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode" // json文件使用prettier
  },
  "[js]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "eslint.options": {
    "extensions": [".js", ".vue", ".ts", ",jsx", ".tsx"] // eslint处理的文件后缀 
  },
  "eslint.validate": ["javascript", "html", "vue"] // eslint检测文件类型
}

lint-staged,husky配置(参考内容

lint-staged提供了暂存区代码检测,而husky提供了各种git钩子,可以在commit之前进行格式化检测。配置如下:在lint-staged喷子命令对js,vue进行prettier代码优化,进行eslint检测;在提交前执行lint-staged命令对暂存文件进行代码检测。

  • 配置lint-staged:
package.json
{
  "husky": {
    "hooks": {
      "pre-commit": "npx lint-staged"
    }
  },
  "lint-staged": {
    "*.{js,vue}": [
      "prettier --write",
      "eslint --fix"
    ]
  }
}
  • lint-staged的一些命令
npx lint-staged --help 
用法: lint-staged [options] 
Options: 
-V, --version 输出版本号 
--allow-empty 当任务撤消所有分阶段的更改时允许空提交(默认值:false) 
-c, --config [path] 配置文件的路径 
-d, --debug 打印其他调试信息(默认值:false) 
-p, --concurrent <parallel tasks> 要同时运行的任务数,或者为false则要连续运行任务(默认值:true) 
-q, --quiet 自己的控制台输出(默认值:false) 
-r, --relative 将相对文件路径传递给任务(默认值:false) 
-x, --shell 跳过任务解析以更好地支持shell(默认值:false) 
-h, --help 输出用法信息
  • 配置husky步骤:
  1. npx husky install 初始化husky
  2. npx husky add .husky/pre-commit 'npx lint-staged' 增加pre-commit钩子及命令
  3. npx husky add .husky/commit-msg 'npx --no-install commitlint --edit $1' 增加commit-msg钩子及命令

commit 规范(参考1参考2)

  1. 新增commitlint.config.js配置文件
  2. 配置 自定义插件和命令,自定义提交信息
module.exports = {
    rules:{
        "self-rule":[2,'always']
    },
    plugins:[
        {
            rules: {
                "self-rule":(msg)=>{
                    const isRightMsg = /^msg:/.test(msg)
                    const isMerge = msg.startWith('Merge')
                    return [isRightMsg||isMerge,"请书写正确提交信息"]
                }
            }
        }
    ]
}

prettier配置

prettier配置需要安装prettier插件,目录下新建.prettierrc.config.js(或者.prettierrc json格式)配置文件。注意vscode扩展会有prettier配置,而prettierrc文件优先级是高于vscode扩展的。

  • 命令
npx prettier . --check  // npx prettier [filepath] [option]
options : 
--check 检测,格式不符合规范的会被warn提醒
--write 修改,格式化文件

配置prettier,直接在prettierrc中按需配置以下配置即可:

  • printWidth 编辑器每行的长度,默认80
  • tabWidth 制表符tab的宽度,默认值是2
  • useTabs 代码缩进是否用制表符tab,默认false
  • semi 是否使用分号,默认true,使用分号
  • singleQuote 是否使用单引号,默认为false,不适用单引号,使用双引号
  • quoteProps 对象属性的引号使用
    • as-needed 仅在需要的时候使用
    • consistent 有一个属性需要引号,就都需要引号
    • preserve 保留用户输入的情况
  • trailingComma 末尾逗号
    • none 末尾没有逗号
    • es5 es5有效的地方保留
    • all 在可能的地方都加上逗号
  • bracketSpacing 字面量对象括号中的空格,默认true
    • true - Example: { foo: bar }.
    • false - Example: {foo: bar}.
  • arrowParens 箭头函数中的括号
    • “avoid” - 在有需要的时候使用. Example: x => x
    • “always” - 一直使用. Example: (x) => x
  • endOfLine 行末尾标识
    • “auto” - 默认使用Maintain existing line endings (mixed values within one file are normalised by looking at what’s used after the first line)
    • “lf” – Line Feed only (\n), common on Linux and macOS as well as inside git repos
    • “crlf” - Carriage Return + Line Feed characters (\r\n), common on Windows
    • “cr” - Carriage Return character only (\r), used very rarely

eslint配置

eslint用于配置对代码语法格式等进行检测并提示,不同于prettier专职于代码的格式化。要使用eslint需要安装eslint扩展插件,同时需要配置.eslintrc.js。如果代码需要通过webpack进行打包,还需要安装eslint-loader,用于wepback打包时进行代码检测。 eslint提供了语法检测和部分代码格式化的任务,这就导致了有时候配置和prettier不一致产生的一些冲突,这种情况可以使用eslint-config-prettier等插件进行解决。

  1. 安装eslint npm install eslint -D
  2. 初始化配置 npx eslint --init ,eslint会自动给出一些配置选择,根据需求可以完成配置文件的初始化。
  3. eslint检测某一文件。npx eslint filename.js
  4. eslint --fix 自动修复错误

初始化会生成.eslintrc.js配置文件,里面可以根据需求进行eslint规则配置。extends可以扩展多种eslint规则配置,避免了手动对常见规则进行配置。官方推荐扩展即eslint:recommended,如果需要扩展vue文件,可以使用plugin:vue/essential,使用ts时扩展@typescript-eslint/eslint-plugin等等(vue,ts等配置需要安装相关插件并在plugin中配置,使用ts时还需要使用@typescript-eslint/parser作为解析器)。

  • 配置eslint
.eslintrc.js
module.exports = {
  env: {
    browser: true,
    es2021: true,
  },
  extends: ["eslint:recommended", "plugin:vue/essential"],
  parserOptions: {
    ecmaVersion: 13,
  },
  plugins: ["vue"],
  rules: {
  },
};

一些eslint自定义rules详细配置(off=0, warn=1, error=2, 如果是数组, 第二项表示参数option)

    "no-console": 0, //不禁用console
    "no-irregular-whitespace": 0, //不规则的空白不允许
    "react/jsx-filename-extension": [1, { extensions: [".js", ".jsx"] }], //文件是.js还是.jsx
    "no-underscore-dangle": 0,
    "array-bracket-spacing": [2, "never"], // 指定数组的元素之间要以空格隔开(,后面)
    "comma-dangle": 2, // 数组和对象键值对最后一个逗号, never参数:不能带末尾的逗号, always参数:必须带末尾的逗号
    indent: [2, 2], // 控制缩进为2
    eqeqeq: 1, // 警告使用全等
    quotes: [2, "single"], //单引号
    "no-console": 0, //不禁用console
    "no-debugger": 1, //警告debugger
    "no-var": 2, //对var禁止
    semi: 2, //强制使用分号
    "semi-spacing": [2, { before: false, after: true }], // 强制分号前后不允许空格
    "no-irregular-whitespace": 0, //不规则的空白不允许
    "no-trailing-spaces": "error", //一行结束后面有空格就发出警告
    "eol-last": 0, //文件以单一的换行符结束
    "no-unused-vars": [2, { vars: "all", args: "after-used" }], //不能有声明后未被使用的变量或参数
    "no-underscore-dangle": 0, //标识符不能以_开头或结尾
    "no-alert": 2, //禁止使用alert confirm prompt
    "no-lone-blocks": 0, //禁止不必要的嵌套块
    "no-class-assign": 2, //禁止给类赋值
    "no-cond-assign": 2, //禁止在条件表达式中使用赋值语句
    "no-const-assign": 2, //禁止修改const声明的变量
    "no-delete-var": 2, //不能对var声明的变量使用delete操作符
    "no-dupe-keys": 2, //在创建对象字面量时不允许键重复
    "no-duplicate-case": 2, //switch中的case标签不能重复
    "no-dupe-args": 2, //函数参数不能重复
    "no-empty": 2, //块语句中的内容不能为空
    "no-func-assign": 2, //禁止重复的函数声明
    "no-invalid-this": 0, //禁止无效的this,只能用在构造器,类,对象字面量
    "no-redeclare": 2, //禁止重复声明变量
    "no-spaced-func": 2, //函数调用时 函数名与()之间不能有空格
    "no-this-before-super": 0, //在调用super()之前不能使用this或super
    "no-undef": 2, //不能有未定义的变量
    "no-use-before-define": 2, //未定义前不能使用
    camelcase: 0, //强制驼峰法命名
    "jsx-quotes": [2, "prefer-double"], //强制在JSX属性(jsx-quotes)中一致使用双引号
    "use-isnan": 2, //禁止比较时使用NaN,只能用isNaN()
  },