• Stars
    star
    712
  • Rank 63,595 (Top 2 %)
  • Language
    JavaScript
  • Created almost 9 years ago
  • Updated about 1 year 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

i-html

HTML
86
star
6

R.js

Internationalisation Library for Javascript
JavaScript
75
star
7

ecmascript-operator-overloading-proposal

A proposal for operator overloading in ECMAScript
64
star
8

proposal-object-freeze-seal-syntax

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

load-testing-node

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

invokers-polyfill

JavaScript
54
star
11

csslex

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

hbs-cli

A CLI for handlebars
JavaScript
43
star
13

LinkyPass

LinkyPass Google Chrome Extension
JavaScript
36
star
14

eslint-plugin-escompat

Report errors for code which wont work in browsers without transpiling
JavaScript
36
star
15

hdx

Refreshing CSS
Rust
35
star
16

proxy-fluent-api

Make Fluent APIs using ES6 Proxies
JavaScript
28
star
17

sort-object-keys

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

gnome-shell-duckduckgo-search-provider

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

eslint-config-strict

ESLint sharable config for strict linting
JavaScript
25
star
20

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
21

mini-observable

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

reading-list

These are the books Im going to read
22
star
23

WebCumberNode

JavaScript
20
star
24

proxy-method-missing

JavaScript
19
star
25

rollup-plugin-brotli

JavaScript
15
star
26

nibstate

TypeScript
14
star
27

getbrightness

JavaScript
14
star
28

travis-ci-node-and-browser-qunit

JavaScript
13
star
29

fdgt

JavaScript
13
star
30

alfred-docker-wizard

Control Docker machines & containers with Alfred
Shell
11
star
31

dotfiles

⚫ These are my dotfiles. There are many like it but these are mine.
Lua
10
star
32

deno-protod

TypeScript
9
star
33

proxy-object-observe

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

custom-attributes

TypeScript
7
star
35

tickrs

Rust
7
star
36

proposal-array-compact

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

Avalanche

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

rollup-plugin-inline-invariant

JavaScript
6
star
39

GitAttributesTest

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

stylelint-config-strict

Stylelint sharable config for strict linting
JavaScript
5
star
41

mqtt-bridges

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

sourcemap-visualiser

JavaScript
4
star
43

deno-varint

Encode/Decode Number/BigInts into an array of Varint bytes
TypeScript
4
star
44

cv

πŸ“„ My curriculum vitae
HTML
3
star
45

probot-flood

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

wsb

JavaScript
3
star
47

sinomocha

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

k-router

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

hubot-seriouslyguys

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

proposal-array-filtermap

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

parse-packagejson-name

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

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
53

NobleClass

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

zero-env

JavaScript
2
star
55

hubot-soon

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

tempus-js.com

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

grunt-hooks

SCM Hook management for Grunt
JavaScript
2
star
58

function-guard

JavaScript
2
star
59

deno-scanner

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

proxy-hide-properties

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

qunit-logging

JavaScript
1
star
62

tar-grab-unpack

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

radon-css

Lightweight alternative to Radium for React
JavaScript
1
star
64

eslint-config-strict-react

eslint-config-strict for React
JavaScript
1
star
65

keithamus

1
star
66

evening-with-tc39

JavaScript
1
star
67

recipes

HTML
1
star
68

proposal-multi-module-files

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

vimstart

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