Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to alphabetize package.json without installing a package?

Tags:

npm

I've been working on lots of old npm packages that have their dependencies all out of order. They're shrinkwrapped packages, so updating dependencies is a bit of work (testing and verifying that the dependency changes didn't break anything), but I'm manually moving some dependencies from the devDependencies key to the dependencies key, and I don't want to do anything except alphabetize them before I commit. Rather than doing it manually, is there an easy way to programmatically alphabetize them with npm?

like image 273
Jo Sprague Avatar asked Dec 23 '15 15:12

Jo Sprague


People also ask

Does the order of packages in package json matter?

json is always alphabetical. Same install order means that you will get the same tree. You can reliably get the same dependency tree by removing your node_modules directory and running npm install whenever you make a change to your package.

Does order of dependencies in package json matter?

json just lists dependencies in alphabetical order by default, so I don't think it matters. You usually won't be manually adding the dependencies to your file, rather you'll be instructing npm to save packages as dependencies when you install them.

How do I skip a package in npm install?

To skip Installation of devDepenencies pass --production flag to npm install ,with the --production flag(or NODE_ENV environment variable set to production ) npm will not install modules listed in devDependencies." To make any module to be part of devDependencies pass --dev while installing.


1 Answers

The sort-package-json package sorts not only dependencies and devDependencies, but other keys as well. I know the original questions didn't ask about the other keys, but I think it's cool to have all keys sorted.

You can simply run:

npx sort-package-json 

Example from the package page:

$ cd my-project  $ cat package.json {   "dependencies": {     "sort-package-json": "1.0.0",     "sort-object-keys": "1.0.0"   },   "version": "1.0.0",   "name": "my-awesome-project" }   $ npx sort-package-json package.json is sorted!   $ cat package.json {   "name": "my-awesome-project",   "version": "1.0.0",   "dependencies": {     "sort-object-keys": "1.0.0",     "sort-package-json": "1.0.0"   } } 

This does not remove the trailing newline like the npm-sort package mentioned by Wolfgang.

Multiple files

$ sort-package-json "my-package/package.json" "other-package/package.json"  $ sort-package-json "package.json" "packages/*/package.json" 
like image 138
Matias Kinnunen Avatar answered Oct 16 '22 17:10

Matias Kinnunen