前端工程化:VS Code 代码自动格式化配置

9,289 阅读8分钟

前置知识:

配置文件:

  • . 文件,此类文件在 mac、linux 系统中默认不显示
  • rc,在软件开发中,"rc" 通常是 "run commands" 的缩写,表示运行命令的配置文件。

后文提及的 .eslintrc.js, .prettierrc.js 都是此类文件。

配置文件优先级:

独立配置文件 > vscode工作区配置 > vscode用户配置

注意:每次配置文件类型的切换,建议重启一下vscode,否则可能不会生效

Editor Config

可以在项目根目录增加一个编辑器统一格式化的配置文件:.editorconfig

此文件在大部分的编辑器都支持。

root = true                         # 根目录的配置文件,编辑器会由当前目录向上查找,如果找到 `roor = true` 的文件,则不再查找[*]
indent_style = space                # 空格缩进,可选"space"、"tab"
indent_size = 4                     # 缩进空格为4个
end_of_line = lf                    # 结尾换行符,可选"lf"、"cr"、"crlf"
charset = utf-8                     # 文件编码是 utf-8
trim_trailing_whitespace = true     # 不保留行末的空格
insert_final_newline = true         # 文件末尾添加一个空行
curly_bracket_next_line = false     # 大括号不另起一行
spaces_around_operators = true      # 运算符两遍都有空格
indent_brace_style = 1tbs           # 条件语句格式是 1tbs[*.js]                              # 对所有的 js 文件生效
quote_type = single                 # 字符串使用单引号[*.{html,less,css,json}]            # 对所有 html, less, css, json 文件生效
quote_type = double                 # 字符串使用双引号[package.json]                      # 对 package.json 生效
indent_size = 2                     # 使用2个空格缩进

每一段在 [] 内填写匹配文件,后面每一行写一条的规则。

插件 EditorConfig for VS Code

配置完成,还无法正常使用,需要安装 VS Code 插件,EditorConfig for VS Code。

image-20230526084513493.png

虽然 .editorconfig 支持的属性很多,但是在这个插件在 VS Code 中仅支持下面的属性:

# .editorconfig 
indent_style
indent_size
tab_width
end_of_line (on save)
insert_final_newline (on save)
trim_trailing_whitespace (on save)

使用

配置完成后,可以通过两种方式来格式化文档:

  • 右键,“格式化文档”,
  • 或 Shift + Alt + F,

此时会调用 VS Code 默认的代码格式化工具,按此 EditorConfig 的配置来进行格式化。

可能遇到的问题:

有些时候对 json 无效。

解决方法:

如果碰到缩进无效的情况,

  1. 点击 VS Code 右下角的“空格: 4": image-20230525110217669.png

  2. 此时,VS Code 正上方弹出选择框,再选择一次 ”空格“ 作为制表符,然后选择 ”4“ 个制表符大小: image-20230525110246879.png

  3. 再点格式化,此时便可以完成格式化。

Prettier

Editor Config 功能有限,需要更强大的功能,则可以选择 Prettier 来完成。

在根目录建一个配置文件 .prettierrc.js:

// .prettierrc.js
module.exports = {
    printWidth: 120,
    tabWidth: 4,
    semi: true,
    singleQuote: true,
    quoteProps: "consistent",
    trailingComma: "es5",
    ...
};

具体配置参考:prettier.io/docs/en/opt…

prettier 推崇的是无配置,如果无特殊配置可以跳过这一步。

Prettier VS Code插件

Prettier 同样需要插件才能生效,安装以下插件,并启用。

image-20230525110821317.png

此时右键,多了“使用...格式化文档”,点击此项,VS Code 正上方弹出来的选择框有 Prettier 选项,表示安装成功。

image-20230525195808703.png

使用

虽然,每次点击右键“使用...格式化文档“都能使用,但是更推荐,把 Prettier 设置成默认格式化程序。

  1. 右键弹出菜单,点击 “使用...格式化文档”,弹出来格式化的选择框
  2. 选择“配置默认格式化程序”,再选择“Prettier”。

image-20230525195808703.png

  1. 再次打开“使用...格式化文档”,此时 Prettier 变成默认值,设置成功。
  2. 下次就可以使用右键“格式化文档”,或 Shift + Alt + F 完成格式化了。

使用命令行格式化

此外还可以通过命令行实现检查与修复:

# 检查当前文件夹的文件是否已经格式化
npx prettier --check .
​
# 按设置的格式对当前文件夹的文件进行格式化
npx prettier --write .

如果有需要也可以将命令写入 package.json

可能遇到的问题

html 换行错乱

image-20230526085213156.png

html 代码换行的时候,标签的箭头被拆散,可以配置 htmlWhitespaceSensitivity 属性为 ignore

    // .prettierrc
    {
        ...,
         "htmlWhitespaceSensitivity": "ignore"
    }

Prettier 经常会碰到不生效的问题。

可能原因:prettierrc.js 文件与 es module 项目冲突,package.json 中如果设置了 "type": "module", 而 perttierc.js 以 commonjs的标准书写,就可能报错。

解决方法:

  1. 新建 .prettierignore 文件忽略 .prettierrc.js
  2. 如果文件无变量,可以写成 json 格式,并命名为:.prettierrc

如果排除以上原因,也可以通过查看日志来找到解决方法:

  1. 打开 VS Code 的终端;
  2. 点击输出 tab,选择“Prettier”,此处能看到 Prettier 的输出

image-20230525142422364.png

  1. 出错信息在["ERROR"] 行。

    ["ERROR" - 14:22:47] Error handling text editor change

    ["ERROR" - 14:22:47] import_mockable2.default.findParentDir is not a function

上面的报错的详细内容中,可以看到使用的 3.0.0-alpha-for-vscode 较新的版本,猜想 VS Code 版本与 Prettier 要求版本不匹配,回退 Prettier 版本到 2.8.8 解决。

网上还有类似的回答,可能是配置文件冲突等原因。具体可以看上面的报错信息。

ESLint

editor config 和 prettier 可以把内容变得好看了,但是要让代码都遵循代码规范,还需要 ESlint 配合。

配置 .eslintrc.js:

module.exports = {
  parserOptions: {
    ecmaVersion: 2020,
    sourceType: 'module',
  },
  rules: {
    'no-unused-vars': 'warn',
    'operator-linebreak': ['error', 'before'],
    ‘quotes’: ['error', 'single'],
  },
};

规则:eslint.org/docs/latest…

ESLint 插件

安装 ESLint VSCode 插件,并启用

image-20230525150853196.png

使用

  1. 安装后,打开 js 文档,如果有代码规范问题,eslint 会在错误的代码下标记波浪线

  2. 鼠标放置上去,即能显示详细的 eslint 报错。 image-20230525210744013.png

  3. 如果需要将显示提示在行末,可以安装 Error lens,可以更方便查看报错信息。 image-20230525210436900.png image-20230525210603058.png

可能出现的问题

ESLint 也会碰到不生效的问题。

可能原因:.eslintrc.js 文件与 es module 项目冲突,package.json 中如果设置了 "type": "module", 而 .eslintrc.js 以 commonjs的标准书写,就可能报错。

解决方法:

  1. 文件名更改 commonjs 文件 eslintrc.cjs
  2. 新建 .eslintignore 文件忽略 .eslintrc.cjs

如果排除以上原因,参考上述的 Prettier 查看日志寻求解决方法:

  1. 打开 VS Code 的终端;
  2. 点击输出 tab,选择“ESLint”,此处能看到 ESLint 的输出

ESLint 和 Prettier 冲突

ESLint 主要负责代码质量,Prettier 主要负责代码格式。但是代码质量也包含了格式部分,所以就会出现两者冲突的情况。

venn-diagram-prettier-eslint.webp

目前已知最大的冲突:

  • ESLint 的换行后操作符放在行首会与和 Prettier 冲突

查看官方 issue: Placing operators at the beginning of lines · Issue #3806 · prettier/prettier · GitHub, Prettier 团队出于各种理由无法解决。此 issue 从 2018 年开始一直处于 open 状态,成员的回答,被 dislike 次数达到 500 次。 也许是被修改的要求次数太多,目前标记到了 4.0 版本的里程碑里。

如果你们团队的规范是 ESLint 的换行后操作符放在行首,可以看看下面的解决方法

解决方法

有两种解决方法:

  1. 删除冲突的规则并将 prettier 作为 eslint 的规则运行。

    可以使用 npm 插件 eslint-config-prettiereslint-plugin-prettier 来处理。

    • eslint-config-prettier 的作用是关闭eslint中与prettier相互冲突的规则。
    • eslint-plugin-prettier 的作用是赋予eslintprettier格式化代码的能力。 安装依赖并修改.eslintrc文件
        npm install --save eslint-config-prettier eslint-plugin-prettier
    

    此方法需要我们删除冲突的内容,需要团队规范做妥协的显然是不合适的。

  2. 修改任务流程:先执行 prettier,然后再执行 eslint,最后再保存。

    Code ➡️ prettier ➡️ eslint --fix ➡️ Formatted Code

    可以使用 npm 插件 prettier-eslint 实现。

    npm install --save-dev prettier-eslint
    

    以下是 prettier-eslint 使用示例:

    const format = require("prettier-eslint");
    
    // notice, no semicolon in the original text
    const sourceCode = "const {foo} = bar";
    
    const options = {
    text: sourceCode,
    eslintConfig: {
    parserOptions: {
    ecmaVersion: 7,
    },
    rules: {
    semi: \["error", "never"],
    },
    },
    prettierOptions: {
    bracketSpacing: true,
    },
    fallbackPrettierOptions: {
    singleQuote: false,
    },
    };
    
    const formatted = format(options);
    
    // notice no semicolon in the formatted text
    formatted; // const { foo } = bar
    

    针对 vue 还有不同子插件要安装。

Prettier Eslint 插件

显然方法 2,是目前更合适的方法,但是这需要写代码自行编排格式化流程,读取配置文件、还有读取具体要格式化的文件来进行格式化。那有没有更好的方法?

有的,在 VSCode 则可以安装使用 Prittier ESLint 插件进行格式化。

image-20230527120015419.png

使用方法跟其他插件一样,右键“使用...进行格式化”,选择 Prettier ESLint 即可。也可以将其设置为默认的格式化工具

另外,Prettier 不是此插件的必配前提,所以最好卸载以上 Prettier 小节提到的 VS Code Prettier 插件。

自动格式化

要想达到工程化,还需要做两步:

  1. 自动格式化,打开 VS Code 设置,勾选上保存时格式化 “Format On Save” 选项,关闭粘贴格式化、输入时格式化的选项。 image-20230527122239696.png 配置完成可以在根目录下出现 .vscode 的文件夹,setting.json 里面保存了刚才的设置。可以直接复制以下内容到 setting.json:

    {
      "files.autoSave": "onFocusChange",
      "editor.formatOnSave": true,
      "eslint.codeActionsOnSave.rules": null,
      "editor.formatOnType": false,
      "editor.formatOnPaste": false,
      "editor.formatOnSaveMode": "file",
      "vs-code-prettier-eslint.prettierLast": false
    }
    
  2. 将以上涉及到的插件配置,“添加到工作区建议”,设置成到项目推荐插件。

    image-20230527122514762.png

  3. .vscode 中,会出现一个 extensions.json 文件,这里记录了刚刚加入建议插件的内容。

    {
      "recommendations": [
        "rvest.vs-code-prettier-eslint",
        "dbaeumer.vscode-eslint",
        "EditorConfig.EditorConfig"
      ]
    }
    
  4. 提交 .vscode 到 git 仓库,这样每个开发者下载代码后,在 VSCode 打开即可推荐插件提示了。

总结

要将代码自动格式化进行工程化,需要以下几个步骤:

  1. 配置 .editorconfig,安装 editorCongig VS Code 插件;
  2. 配置 prettier(可选),安装 prettier npm 插件;
  3. 配置 eslint,安装 eslint npm 插件及 VS Code 插件;
  4. 安装 Prettier ESLint 插件,处理 prettier 和 eslint 的兼容问题;
  5. 配置保存时自动格式化;
  6. 将本地配置保存到工作区;
  7. 提交配置到 git。

这样,前端工程的自动格式化配置就完成了,团队成员写完代码保存时格式化也已经完成,不再需要消耗时间,手动去修改。

开始愉快的写代码吧!

参考

eslint-plugin-prettier

eslint-config-prettier

prettier-eslint

.editorconfig配置统一编辑器配置

代码美化神器——Prettier使用详解

用Prettier和ESLint自动格式化修复JavaScript代码

解决Eslint 和 Prettier 之间的冲突 - 掘金 (juejin.cn)