I created a custom printer for Prettier to format enum
declarations in a specific way. However, when using my custom printer, all comments inside the enum
are removed.
I want my printer to only modify specific parts of the formatting (e.g., alignment of the =
operator) while preserving the original Prettier behavior for everything else, including comments.
Is there a way to extend the default Prettier printer instead of fully replacing it?
I implemented a custom printer, but it seems to override the entire printing process, causing:
Loss of comments inside enum
.
Application of different formatting rules, such as trailing commas and spacing changes.
Here is the relevant code:
import { AstPath, Doc, ParserOptions, doc } from 'prettier'
const { join, group, indent, hardline } = doc.builders
type TSEnumMember = {
id: { name: string }
initializer?: unknown
}
type TSEnumDeclaration = {
type: 'TSEnumDeclaration'
id: { name: string }
members: TSEnumMember[]
}
export const printEnum = (path: AstPath<TSEnumDeclaration>, options: ParserOptions, print: TCallbackPrint): Doc => {
const maxMemberLength = path.node.members.reduce((max, member) => Math.max(max, member.id.name.length), 0)
const memberDocs = path.map((memberPath) => {
const member = memberPath.node
const spacing = ' '.repeat(maxMemberLength - member.id.name.length)
if (member.initializer !== undefined) {
return [
`${member.id.name}${spacing} = `,
memberPath.call(print, 'initializer'),
',',
]
}
return [member.id.name, ',']
}, 'members')
const joinedMembers = join(hardline, memberDocs)
return group([
`enum ${path.node.id.name} {`,
indent([hardline, joinedMembers]),
hardline,
'}',
])
}
GitHub repo: