Keeping your package.json file organised

It's always nice to have an agreed standard for files. It makes finding information predictable and reduces diff noise when working with a team. One file that could do with a standard is the package.json file. As devs, we put a lot of information in there, usually the same information from project-to-project, consistently organising this could help greatly when reviewing packages.

This is where Andrew Powell's plugin for Prettier comes to the rescue. It's called prettier-plugin-package and it uses the power of Prettier to automatically organise your package file.

Quick setup

Install the dev dependencies:

# Using Yarn
yarn add -D prettier prettier-plugin-package husky

# Or using npm
npm i -D prettier prettier-plugin-package husky

Update your scripts in package.json:

{
"scripts": {
"pretty-package": "prettier --write package.json"
},
"husky": {
"hooks": {
"pre-commit": "yarn pretty-package && git add package.json"
}
}
}

Dependencies

Prettier

Prettier probably doesn't need much introduction these days: it's a formatter that reduces the mental overload of how to aesthetically display your code. If you're not using it, why not? I cannot imagine going back to a pre-Prettier world.

prettier-plugin-package

The focus of this article, and it's in the name: a plugin for Prettier that helps automatically organise your package file. It's zero-config; simply install and point Prettier at your file.

Husky

Husky describes itself as "Git hooks made easy". This will allow us to run Prettier on our package file before every commit. More on this below.

pretty-package script

"pretty-package": "prettier --write package.json"

This will run Prettier (including the added plugin) on the package file and write the changes.

Husky

"husky": {
"hooks": {
"pre-commit": "yarn pretty-package && git add package.json"
}
}

When you commit your code, Prettier will run against the package file, then stage the changes into the same commit. Meaning if you make changes to the package file, you do not need to manually run any scripts; relax, everything is done for you. At this stage, you may want to run Prettier on your whole project, or use ESLint, but I'll leave that for another post.