如何修改Prettier对JavaScript类的格式化行为并编写自定义插件?
修改Prettier类内部首行空行的格式化行为
当前Prettier格式化结果
class Foo { bar = 1 }
期望的格式化结果
class Foo { bar = 1 }
实现方法
方法一:编写自定义Prettier插件
通过重写AST节点的打印逻辑,修改类块的格式化行为:
- 创建插件文件(比如
prettier-plugin-class-empty-line.js),写入以下代码:
module.exports = { parsers: { babel: { astFormat: "estree", print: { ClassBody(path, options, print) { const contentNodes = path.map(print); // 在类块内容前插入空行,保留原有缩进规则 return [ "{", "\n\n", options.indent(contentNodes.join(options.lineEnding)), "\n}" ]; } } }, // 如果使用TypeScript,需要添加typescript解析器的重写 typescript: { astFormat: "typescript-estree", print: { ClassBody(path, options, print) { const contentNodes = path.map(print); return [ "{", "\n\n", options.indent(contentNodes.join(options.lineEnding)), "\n}" ]; } } } } };
- 在项目的
.prettierrc中配置使用该插件:
{ "plugins": ["./prettier-plugin-class-empty-line.js"] }
方法二:结合ESLint自定义规则补充校验
如果不想编写插件,可通过ESLint自定义规则强制类内部首行空行:
- 安装依赖:
npm install eslint eslint-plugin-prettier eslint-config-prettier --save-dev - 在
.eslintrc.js中添加自定义规则:
module.exports = { extends: ["plugin:prettier/recommended"], rules: { "prettier/prettier": ["error"], // 自定义规则:类块内部首行必须有空行 "class-block-first-line-empty": ["error", { create(context) { return { ClassBody(node) { if (node.body.length === 0) return; const firstClassItem = node.body[0]; const openingBrace = context.getSourceCode().getTokenBefore(firstClassItem); if (openingBrace?.value === "{") { const braceLine = openingBrace.loc.end.line; const firstItemLine = firstClassItem.loc.start.line; if (firstItemLine - braceLine <= 1) { context.report({ node: firstClassItem, message: "类内部首行需保留空行" }); } } } }; } }] } };
- 运行ESLint自动修复:
npx eslint --fix src/**/*.js
注意事项
- 自定义插件需注意兼容项目使用的解析器(如Babel/TypeScript),不同解析器需单独重写对应逻辑
- ESLint规则方式是通过校验强制格式,需配合
--fix命令完成自动修复,属于Prettier规则的补充
内容的提问来源于stack exchange,提问作者BrunoLM
相关产品推荐
相关产品推荐

