npm: Sort package.json

Run npx sort-package-json.

Use the sort-package-json package:

npx sort-package-json

This takes about 4–8 seconds on my machine because npx has to first download the package. If that's too slow for you, install the package globally:

#  i =   install
# -g = --global
npm i -g sort-package-json

Then you can run just:


And it will take less than a second.

Of course you can also install the package locally and even run it in Git's pre-commit hook (using Husky) or in your CI pipeline. More options are mentioned in the package's documentation.

Source: My own Stack Overflow answer