• Stars
    star
    712
  • Rank 61,152 (Top 2 %)
  • Language
    JavaScript
  • Created over 8 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Sort an Object or package.json based on the well-known package.json keys

Sort Package.json

Build Status NPM Version

CLI

Run via npx ([email protected]+ required)

npx sort-package-json

Install

npm install --global sort-package-json

Usage

$ 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!

Found 1 file.
1 file successfully 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"
  }
}

CLI also supports multi file paths or glob - so you can give it a bunch of package.json file(s) to sort.

$ sort-package-json "my-package/package.json" "other-package/package.json"

$ sort-package-json "package.json" "packages/*/package.json"

--check flag

When you want to check if your files are sorted, you can run CLI with the --check flag (or -c). This will output a list of not sorted files, if any.

$ sort-package-json "**/package.json" --check

Found 5 files.
5 files were already sorted.

$ sort-package-json "**/package.json" --check
foo/package.json
bar/package.json

Found 5 files.
3 files were not sorted.
2 files were already sorted.

--quiet flag

In order to silence any successful output, you can run CLI with the --quiet flag (or -q). This will stop the CLI from outputting if it runs successfully, but won't effect error messages and the exit code.

$ sort-package-json "**/package.json" --check --quiet
$ sort-package-json "**/package.json" --quiet

API

Install

npm install --save-dev sort-package-json

Usage

sortPackageJson(packageJson, options?)

Pass a JSON string, return a new sorted JSON string.
Pass a JSON object, return a new sorted JSON object.

import sortPackageJson from 'sort-package-json'

const packageJsonString = `{
  "dependencies": {
    "sort-package-json": "1.0.0",
    "sort-object-keys": "1.0.0"
  },
  "version": "1.0.0",
  "name": "my-awesome-project"
}`

console.log(sortPackageJson(packageJsonString))
/* => string:
{
  "name": "my-awesome-project",
  "version": "1.0.0",
  "dependencies": {
    "sort-object-keys": "1.0.0",
    "sort-package-json": "1.0.0"
  }
}
*/

const packageJsonObject = JSON.parse(packageJsonString)
console.log(sortPackageJson(packageJsonObject))
/* => object:
{
  name: 'my-awesome-project',
  version: '1.0.0',
  dependencies: {
    'sort-object-keys': '1.0.0',
    'sort-package-json': '1.0.0'
  }
}
*/

options.sortOrder

Type: string[] | Function
Default: sortPackageJson.sortOrder

Custom ordering array or comparator function.

If an array, sort keys in ordering of options.sortOrder.

Notice: fields not in this array, will still sort by defaultSortOrder

const sorted = sortPackageJson(packageJsonObject, {
  sortOrder: ['version'],
})

console.log(Object.keys(sorted))

// -> [ 'version', 'name', 'dependencies' ]
//                 ^^^^^^^^^^^^^^^^^^^^^^
//                 `name` and `dependencies` are sorted by defaultSortOrder

If a function, sort fields by Array#sort(options.sortOrder)

const sorted = sortPackageJson(packageJsonObject, {
  sortOrder(left, right) {
    return left.localeCompare(right)
  },
})

console.log(Object.keys(sorted))

// -> [ 'dependencies', 'name', 'version' ]

Related tools

Supported Libraries

Alphabetically ordered.

Automatically Sort

The package.json file can be sorted automatically before committing.

npm install husky lint-staged --save-dev
npm pkg set scripts.prepare="husky install"
npm run prepare
npx husky add .husky/pre-commit "npx lint-staged"

Add the following to your package.json file

{
  "lint-staged": {
    "package.json": "sort-package-json"
  }
}

See Husky and lint-staged for more information.

PFAQ: Potential Frequently Asked Questions

How does it sort?

It sorts using sort-object-keys. It sorts using the well-known keys of a package.json. For the full list check the default rules. It sorts sub-keys too - sometimes by a well-known order, other times alphabetically. The initial order was derived from the package.json docs with a few extras added for good measure.

It doesn't sort X?

Cool. Send a PR! It might get denied if it is a specific vendor key of an unpopular project (e.g. "my-super-unknown-project"). We sort keys like "browserify" because it is a project with millions of users. If your project has, say, over 100 users, then we'll add it. Sound fair?

Isn't this just like Project X?

Could be. I wanted this one because at the time of writing, nothing is:

  • Zero config
  • Able to be used in a library
  • Quiet (i.e. not spitting out annoying log messages, when used in a library mode)

I would like this tool to be configurable with a config file or command line arguments.

The lack of configuration here is a feature, not a bug. The intent of this tool is that a user can open a package json and always expect to see keys in a particular order. If we add a configuration for this tool, then that promise is broken, as users will first need to look at the configuration for each project to learn the ways in which this tool will change the package.json. The structure of the package.json should always be predictable & deterministic from project to project. I think the reason why this project is well used is because it is not another "tool" you have to set up with yet another JSON file and more cruft in your project to support it. You run a command and it does what it says on the tin.

A lot of people who ask for configuration cite the use case that they simply don't like the given order that exists and want to make sweeping changes. To me this seems far better suited to simply making a fork of this project as then you can go far further than specifying configuration.

What?! Why would you want to do this?!

Well, it's nice to have the keys of a package.json in a well sorted order. Almost everyone would agree having "name" at the top of a package.json is sensible (rather than sorted alphabetically or somewhere silly like the bottom), so why not the rest of the package.json?

More Repositories

1

jwerty

⌨ Awesome handling of keyboard events
JavaScript
1,213
star
2

npm-scripts-example

An example of how to use NPM scripts over Grunt/Gulp & Friends. http://blog.keithcirkel.co.uk/how-to-use-npm-as-a-build-tool
JavaScript
831
star
3

hashmark

Take contents of a file (or stdin), and output as new file with a hash in the name
JavaScript
195
star
4

tempus

Tempus - Time for a new Date()
JavaScript
94
star
5

R.js

Internationalisation Library for Javascript
JavaScript
75
star
6

ecmascript-operator-overloading-proposal

A proposal for operator overloading in ECMAScript
64
star
7

proposal-object-freeze-seal-syntax

A JavaScript TC39 proposal for Object.freeze & Object.seal syntax
59
star
8

load-testing-node

Various setups for Load Balancing multiple Node.js processes on a single VM
Ruby
57
star
9

invokers-polyfill

JavaScript
44
star
10

hbs-cli

A CLI for handlebars
JavaScript
43
star
11

csslex

A very small and very fast spec compliant css lexer
JavaScript
39
star
12

LinkyPass

LinkyPass Google Chrome Extension
JavaScript
36
star
13

eslint-plugin-escompat

Report errors for code which wont work in browsers without transpiling
JavaScript
29
star
14

proxy-fluent-api

Make Fluent APIs using ES6 Proxies
JavaScript
28
star
15

sort-object-keys

Sort an object's keys, including an optional key list
JavaScript
28
star
16

hdx

Refreshing CSS
Rust
26
star
17

gnome-shell-duckduckgo-search-provider

This is a Search Provider for Gnome Shell, and it provides DuckDuckGo Search functionality.
TypeScript
25
star
18

eslint-config-strict

ESLint sharable config for strict linting
JavaScript
25
star
19

postcss-hash

PostCSS plugin to replace output file names with HASH algorithms (md5, sha256, sha512, etc) and string length of your choice - for cache busting
JavaScript
24
star
20

reading-list

These are the books Im going to read
22
star
21

mini-observable

A mini implementation of TC39 observables, plus some utils!
TypeScript
22
star
22

WebCumberNode

JavaScript
20
star
23

proxy-method-missing

JavaScript
19
star
24

rollup-plugin-brotli

JavaScript
15
star
25

nibstate

TypeScript
14
star
26

getbrightness

JavaScript
14
star
27

fdgt

JavaScript
14
star
28

travis-ci-node-and-browser-qunit

JavaScript
13
star
29

alfred-docker-wizard

Control Docker machines & containers with Alfred
Shell
11
star
30

dotfiles

âš« These are my dotfiles. There are many like it but these are mine.
Lua
10
star
31

deno-protod

TypeScript
9
star
32

proxy-object-observe

An Object.observe inspired util, based on ES6 proxies
JavaScript
7
star
33

custom-attributes

TypeScript
7
star
34

proposal-array-compact

A proposal for adding a `compact()` method to Arrays
HTML
6
star
35

Avalanche

A web-based GUI for torrent applications (such as rTorrent)
JavaScript
6
star
36

rollup-plugin-inline-invariant

JavaScript
6
star
37

GitAttributesTest

Showing how gitattributes can help you maintain a config file while keeping your config secrets from commits
Shell
5
star
38

deno-varint

Encode/Decode Number/BigInts into an array of Varint bytes
TypeScript
5
star
39

stylelint-config-strict

Stylelint sharable config for strict linting
JavaScript
5
star
40

mqtt-bridges

A platform for bridging APIs into mqtt messages
JavaScript
4
star
41

sourcemap-visualiser

JavaScript
4
star
42

cv

📄 My curriculum vitae
HTML
3
star
43

wsb

JavaScript
3
star
44

sinomocha

Sinon.JS integration for the Mocha test harness
JavaScript
3
star
45

k-router

A MVC/MVT style router for Connect/Express apps
JavaScript
3
star
46

hubot-seriouslyguys

A hubot script for showing a 'Srsly Guise' gif when someone says 'Seriously Guys' or 'Srsly Guise'
CoffeeScript
3
star
47

probot-flood

A bot that automatically locks issues if they get flooded with comments
JavaScript
3
star
48

proposal-array-filtermap

A proposal for adding a `filterMap()` method to Arrays
HTML
3
star
49

deno-protoc-parser

Parse Google Protocol Buffer DSL into an AST, which can be converted into JSON or back into the Protocol Buffer DSL.
TypeScript
2
star
50

NobleClass

A JavaScript ES5 compliant Class implementation for Browser and NodeJS
JavaScript
2
star
51

zero-env

JavaScript
2
star
52

function-guard

JavaScript
2
star
53

tempus-js.com

Website for Tempus (https://github.com/tempusjs/tempus)
HTML
2
star
54

grunt-hooks

SCM Hook management for Grunt
JavaScript
2
star
55

parse-packagejson-name

Parse an npm package name and returns some mildly interesting details about it
JavaScript
2
star
56

hubot-soon

A hubot script for showing a 'SOON' image when someone says 'soon'
CoffeeScript
2
star
57

deno-scanner

Take a Deno.Reader and perform Lexical Analysis/Tokenization on it, returning a stream of tokens.
TypeScript
2
star
58

qunit-logging

JavaScript
1
star
59

proxy-hide-properties

Hide a property from all conceivable ways of being detected
JavaScript
1
star
60

radon-css

Lightweight alternative to Radium for React
JavaScript
1
star
61

eslint-config-strict-react

eslint-config-strict for React
JavaScript
1
star
62

tar-grab-unpack

Node.js utlity to grab tar files and unpack them
JavaScript
1
star
63

keithamus

1
star
64

evening-with-tc39

JavaScript
1
star
65

recipes

HTML
1
star
66

proposal-multi-module-files

A JavaScript TC39 Proposal for expressing multiple ES6 modules in a single file
JavaScript
1
star
67

vimstart

specify custom VIM start screen text using custom shell scripts
Vim Script
1
star