Coping strategy for npm --save reformatting package.json
If you use
npm install --save to install packages, npm updates dependencies in
package.json and re-indents the file to use 2 spaces. Depending on your coding standards this might not be to your liking.
To makes matters worse, committing a change to
package.json with varying indentation creates hard-to-read git diffs. Adding one dependency causes the diff look like the whole file changed.
Introducing jsonlint - JSON validator and formatter
You can use a JSON pretty-printer to make
package.json use your coding standards. One such implementation is jsonlint that acts as both a validator and a formatter.
You can use jsonlint to reformat
package.json with 4 spaces using:
--in-place option instructs jsonlint to rewrite the file with new formatting. By default, jsonlint uses 4 spaces as indentation, but you can change it with the
jsonlint -i as part of build
To make sure your
package.json is automatically reformatted and not relying on the developer to do it, you can add reformatting as part of your build process.
Let's assume you're using
"scripts" to define the build commands of your project. First, you'd add the dependency on jsonlint to your project.
Then, you'd chain running jsonlint as part of your build commands using the
&&-operator. Note that when installed as a dependency, the jsonlint binary is available in path in package.json scripts.
to get lost with Node.js