什么是 Prettier?
Prettier 是一个有态度的代码格式化程序,支持:
¥Prettier is an opinionated code formatter with support for:
JavaScript(包括实验性功能)
¥JavaScript (including experimental features)
它删除所有原始风格 * 并确保所有输出的代码都符合一致的风格。(见此 博文)
¥It removes all original styling* and ensures that all outputted code conforms to a consistent style. (See this blog post)
Prettier 将你的代码考虑到行的长度,并从头开始重新打印它。
¥Prettier takes your code and reprints it from scratch by taking the line length into account.
例如,采用以下代码:
¥For example, take the following code:
foo(arg1, arg2, arg3, arg4);
它适合单行,因此它将保持原样。然而,我们都遇到过这种情况:
¥It fits in a single line so it’s going to stay as is. However, we've all run into this situation:
foo(reallyLongArg(), omgSoManyParameters(), IShouldRefactorThis(), isThereSeriouslyAnotherOne());
突然间,我们之前调用函数的格式就崩溃了,因为它太长了。Prettier 将为你完成重印它的艰苦工作:
¥Suddenly our previous format for calling function breaks down because this is too long. Prettier is going to do the painstaking work of reprinting it like that for you:
foo(
reallyLongArg(),
omgSoManyParameters(),
IShouldRefactorThis(),
isThereSeriouslyAnotherOne(),
);
Prettier 在整个代码库中强制执行一致的代码风格(即不会影响 AST 的代码格式),因为它通过解析原始风格 * 并使用自己的规则重新打印解析后的 AST,这些规则将最大行长度纳入其中 账户,必要时封装代码。
¥Prettier enforces a consistent code style (i.e. code formatting that won’t affect the AST) across your entire codebase because it disregards the original styling* by parsing it away and re-printing the parsed AST with its own rules that take the maximum line length into account, wrapping code when necessary.
如果你想了解更多信息,这两个会议演讲是很好的介绍:
¥If you want to learn more, these two conference talks are great introductions:
脚注
¥Footnotes
¥* Well actually, some original styling is preserved when practical—see empty lines and multi-line objects.