Prettier to Beautify Your Code
Learn how to use and configure Prettier to beautify and format your code.
We'll cover the following
Beautifying code with Prettier
Prettier describes itself as “an opinionated code formatter.” First introduced in 2017, it’s already soared to two million downloads per week from the npm registry. Using Prettier for the first time feels like a breath of fresh air. No more worrying about insignificant stylistic details as you work. No more arguments with your team about what’s most readable. Just let the formatter take care of it. Let’s add Prettier to our project.
-
Since we’re using ESLint, we want the
prettier-eslint
command, which ensures that Prettier formats our code in a consistent manner with our ESLint config. To get that command, install theprettier-eslint-cli
package:$ npm install --save-dev prettier-eslint-cli@4.7.1 + prettier-eslint-cli@4.7.1
-
Try running
prettier-eslint
against our test suite:$ npx prettier-eslint tests/palindromes.test.js const palindromes = require("../palindromes"); describe("palindromes()", () => { it("correctly identifies one-word palindromes", () => { expect(palindromes("madam")).toEqual(["madam"]); expect(palindromes("racecar")).toEqual(["racecar"]); }); }); success formatting 1 file with prettier-eslint
Prettier read tests/palindromes.test.js
and emitted a formatted version as its output. It didn’t change the file itself. If you typed the original code exactly as presented in the course, there’s only one change in the formatted version. The strings are double-quoted rather than single-quoted, per Prettier’s default configuration. Thankfully, if you don’t like Prettier’s double-quote absolutism, you have the power to change it.
Below you can implement what you have learned above. Install the library given above and then run the command
npx prettier-eslint tests/palindromes.test.js
.
Get hands-on with 1400+ tech skills courses.