prettier Show archive.org snapshot calls itself an opinionated code formatter. I recommend using it for your JavaScript and TypeScript code.
prettier only concerns itself with the formatting of your JavaScript (and also some other file types like json or yaml). When you use it, it has an opinion on every single whitespace and linebreak, as well as a few other things. You renamed a variable and now your line is a bit longer than looks good? prettier will reformat your code.
This might not work for you if you have strong opinions yourself. You cannot configure it to do exactly what you want, there a deliberately few config options. But if you can accept its taste, it will save you a lot of time.
Example
This is formatted by prettier using the config below. It probably looks "nothing special", which is good.
export async function deleteComment({ uuid }: { uuid: string }) {
return withAuthorizedUser(async ({ accessibleBy }) => {
const prisma = await prismaClient()
const comment = await prisma.comment.findUnique({
where: { uuid },
include: { file: true },
})
if (!comment) {
return notFound()
}
await prisma.comment.delete({
where: {
uuid,
AND: accessibleBy('delete').Comment,
},
})
revalidatePath(`/backend/files/${comment.file.directoryUuid}`, 'layout')
return 'ok'
})
}
Set up prettier
First, add the prettier
npm package.
Then, add a config file. I recommend this one:
// prettier.config.mjs
/**
* @see https://prettier.io/docs/en/configuration.html
* @type {import("prettier").Config}
*/
const config = {
semi: false, // no semicolons
singleQuote: true, // prefer single quote
printWidth: 100, // increase line length a bit
}
export default config
Add two scripts to your package.json
:
{
"scripts": {
"format": "prettier . --write",
"check-format": "prettier . --check"
}
}
If you run yarn check-format
/ npm run check-format
it might start complaining about a lot of files you don't want it to touch, for example some json or yaml fixtures, some vendor code etc. To fix this, add a .prettierignore
, same format as .gitignore
.
Then run yarn format
/ npm run format
, and let it reformat all your existing code.
Editor config
Most modern editors have support for prettier. You can usually either configure a shortcut to auto-format, or you can format on save.
Eslint
If you use elsint, you might start to get a lot of errors, where prettier's and eslint's ideas of proper formatting misalign.
If so, I recommend you use the opportunity and upgrade eslint. Newer versions have removed all stylistic rules and will not complain about any of prettier's choices.
We have an eslint configuration guide, but you'll have to drop all the stylistic
plugin and all the related rules.
CI
If you care, you can add a CI job that simply runs yarn check-format
.