• Stars
    star
    143
  • Rank 257,007 (Top 6 %)
  • Language
    TypeScript
  • Created over 7 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

Prettier formatter for package.json files

Prettier package.json

CI npm

prettier-package-json is a JSON formatter inspired by prettier. It removes all original styling and ensures that the outputted package.json conforms to a consistent style. By default it uses opinionated defaults but can be configured to your individual needs.

Features

Consistent key order

Keys in package.json will be sorted in an opinionated order but may be configured to your own preferences.

Input:

{
  "description": "Prettier formatter for package.json files",
  "name": "prettier-package-json",
  "license": "MIT",
  "version": "1.0.1",
  "author": "Cameron Hunter <[email protected]>"
}

Output:

{
  "name": "prettier-package-json",
  "description": "Prettier formatter for package.json files",
  "author": "Cameron Hunter <[email protected]>",
  "license": "MIT",
  "version": "1.0.1"
}

Sensibly sorted scripts

The scripts field is sorted alphabetically but keeps pre and post scripts surrounding their named script.

Input:

{
  "name": "prettier-package-json",
  "version": "1.0.1",
  "scripts": {
    "test": "test",
    "pretest": "pretest",
    "version": "version",
    "postversion": "postversion",
    "build": "build"
  }
}

Output:

{
  "name": "prettier-package-json",
  "version": "1.0.1",
  "scripts": {
    "build": "build",
    "pretest": "pretest",
    "test": "test",
    "version": "version",
    "postversion": "postversion"
  }
}

Expand/contract author, contributors, and maintainers

The author, contributors and maintainers fields will be shortened to their string versions and sorted by name. Use the --expand-users option if you prefer user objects.

Input:

{
  "name": "prettier-package-json",
  "version": "1.0.1",
  "author": {
    "name": "Cameron Hunter",
    "email": "[email protected]",
    "url": "https://cameronhunter.co.uk"
  },
  "contributors": ["Barry", "Adam <[email protected]>"]
}

Output:

{
  "name": "prettier-package-json",
  "version": "1.0.1",
  "author": "Cameron Hunter <[email protected]> (https://cameronhunter.co.uk)",
  "contributors": ["Adam <[email protected]>", "Barry"]
}

Filter and sort files field

Some files are included or excluded automatically by npm, these are removed from the files field before sorting alphabetically.

Input:

{
  "name": "prettier-package-json",
  "version": "1.0.1",
  "main": "src/index.js",
  "files": [
    "src/index.js",
    "src",
    "CHANGELOG.md",
    "readme.md",
    "package-lock.json"
  ]
}

Output:

{
  "name": "prettier-package-json",
  "version": "1.0.1",
  "main": "src/index.js",
  "files": ["src"]
}

Usage

Install:

yarn add prettier-package-json --dev

You can install it globally if you like:

yarn global add prettier-package-json

We're defaulting to yarn but you can use npm if you like:

npm install [-g] prettier-package-json

CLI

Run prettier-package-json through the CLI with this script. Run it without any arguments to see the options.

To format a file in-place, use --write. You may want to consider committing your file before doing that, just in case.

prettier-package-json [opts] [filename]

In practice, this may look something like:

prettier-package-json --write ./package.json

Pre-commit hook for changed files

You can use this with a pre-commit tool. This can re-format your files that are marked as "staged" via git add before you commit.

1. lint-staged

Install it along with husky:

yarn add lint-staged husky --dev

and add this config to your package.json:

{
  "scripts": {
    "precommit": "lint-staged"
  },
  "lint-staged": {
    "package.json": ["prettier-package-json --write", "git add"]
  }
}

See https://github.com/okonet/lint-staged#configuration for more details about how you can configure lint-staged.

2. bash script

Alternately you can just save this script as .git/hooks/pre-commit and give it execute permission:

#!/bin/sh
packagejsonfiles=$(git diff --cached --name-only --diff-filter=ACM | grep 'package\.json$' | tr '\n' ' ')
[ -z "$packagejsonfiles" ] && exit 0

diffs=$(node_modules/.bin/prettier-package-json -l $packagejsonfiles)
[ -z "$diffs" ] && exit 0

echo "here"
echo >&2 "package.json files must be formatted with prettier-package-json. Please run:"
echo >&2 "node_modules/.bin/prettier-package-json --write "$diffs""

exit 1

API

The API has two functions, exported as format and check. Usage is as follows:

import { format, check } from 'prettier-package-json';

const options = {}; // optional

format(json, options);
check(json, options);

check checks to see if the file has been formatted with prettier-package-json given those options and returns a Boolean. This is similar to the --list-different parameter in the CLI and is useful for running in CI scenarios.

CI

For usage in CI scenarios, you can use the --list-different CLI flag. The command will list all invalid files and return with a proper default error code, so that in case of an error or invalid file the build pipeline automatically fails.

These are the status codes:

  • 0: all files valid, no error occured.
  • 1: an error ocurred, for example a JSON parse error. See message on stderr for details.
  • 2: not all files are valid.

These exit codes are only set when in --list-different mode.

Options

prettier-package-json ships with a handful of customizable format options, usable in both the CLI, API, and configuration file.

Option Default CLI override API override
Tab Width - Specify the number of spaces per indentation-level. 2 --tab-width <int> tabWidth: <int>
Tabs - Indent lines with tabs instead of spaces. false --use-tabs useTabs: <bool>
Expand Users - Expand author and contributors into objects. false --expand-users expandUsers: <bool>
Key Order - Specify the order of keys. See default options --key-order <comma,separated,list...> keyOrder: <array|function>

A configuration file will be searched for using cosmiconfig rules:

  • prettier-package-json field in package.json.
  • prettier-package-json file (JSON or YAML), extentionless "rc" file.
  • prettier-package-json file with the extensions .json, .yaml, .yml, .js, or .cjs.
  • prettier-package-json.config.js or prettier-package-json.config.cjs CommonJS module.

Configuration file may also be passed using the --config CLI parameter.

Contributing

See CONTRIBUTING.md.

More Repositories

1

local-ssl-proxy

Simple SSL HTTP proxy using a self-signed certificate. Intended for local development only.
TypeScript
629
star
2

alexa

Monorepo of libraries used for Amazon Alexa development
JavaScript
38
star
3

ink-markdown

Render markdown text using Ink
TypeScript
29
star
4

ink-monorepo

Monorepo for Ink related packages
TypeScript
27
star
5

jest-watch-directories

Jest watch plugins to filter to directories, lerna packages, or yarn workspaces
JavaScript
26
star
6

generator-alexa-skill

A Yeoman generator for scaffolding an ES2015 Alexa Skill for AWS Lambda
JavaScript
22
star
7

flight-storage

Store JSON data using multiple storage backends
JavaScript
20
star
8

glacier-cli

Amazon AWS Glacier command line interface for Linux, Mac and Windows
Java
19
star
9

jsonymize

Anonymize JSON values, easily.
JavaScript
16
star
10

graphql-shorthand-parser

Parse GraphQL schemas from shorthand notation
JavaScript
15
star
11

unicode-tr51-emoji

Emoji data extracted from Unicode Technical Report #51 v1.0 – v5.0
JavaScript
15
star
12

alexa-annotations

Create Alexa Skills using ES6 classes, promises, and ES7 decorators
JavaScript
15
star
13

sonos-bluetooth

Trying to make a Raspberry Pi Bluetooth A2DP to Sonos bridge
Shell
11
star
14

alexa-reasonml

An example Alexa skill written in ReasonML
OCaml
11
star
15

flight-viewport

Responsive breakpoint component for Flight
JavaScript
10
star
16

divine-player

HTML5 video player that degrades to Flash if necessary
JavaScript
10
star
17

flight-geolocation

Geo-location component for Flight
JavaScript
10
star
18

grunt-fontfactory

Grunt task which creates a font from multiple SVG glyph files
JavaScript
9
star
19

rollup-plugin-pegjs

Import PEG.js grammars as parsers directly in your code
JavaScript
7
star
20

emoji-lang

Calculate emoji positioning within strings
JavaScript
7
star
21

flight-js-snippets

Flight JS Snippets for Sublime Text
6
star
22

blackjack-spine

Blackjack written using SpineJS and Bootstrap
JavaScript
6
star
23

kanye-alexa-skill

An Alexa skill for the Amazon Echo. It reads Kanye's tweets.
JavaScript
5
star
24

event-matchers

Composable functions for handling event callbacks in JS
JavaScript
5
star
25

HappyDays

Android application that notifies you of your contacts' birthdays and anniversaries.
Java
4
star
26

flight-conductor

A media timeline conductor inspired by popcorn.js
JavaScript
4
star
27

alexa-playground

Play with Alexa skills and requests
JavaScript
4
star
28

social-media-alexa-skill

An Alexa skill for the Amazon Echo – it reads trending topics from Social Media.
JavaScript
4
star
29

space-alexa-skill

Alexa skill for the Amazon Echo – it plays audio from the NASA API
JavaScript
3
star
30

shift

A few jscodeshift transforms
JavaScript
3
star
31

twitter-lang

A formal grammar defining tweet text
JavaScript
3
star
32

divine-card

Improving Vine's card implementation
JavaScript
3
star
33

npm-config-user-agent-parser

Parser for process.env.npm_config_user_agent
JavaScript
2
star
34

sort-order

Combine a series of sort functions to create complex sort orders.
TypeScript
2
star
35

flight-orientation-app

iOS7-ish parallax homescreen made using HTML5, CSS3 and Flight JS
JavaScript
2
star
36

regulation

A monorepo of libraries and tools for parsing and converting Regulation lang to regular expressions
JavaScript
2
star
37

flight-edge

Triggers an event when entering or leaving a screen edge
JavaScript
2
star
38

astcenc

A command-line tool for compressing and decompressing images using the ASTC texture compression standard.
Shell
1
star
39

airport-search-alexa-app

Amazon Alexa skill for searching for airport details
JavaScript
1
star
40

superheroes-alexa-skill

An Alexa skill for the Amazon Echo – it reveals superheroes identities.
JavaScript
1
star
41

gif-pause

Click to play/pause animated GIFs
1
star
42

flight-orientation

A flight component for device orientation
JavaScript
1
star
43

berry-bin-bug

Repository demonstrating a Yarn 2.0 issue
JavaScript
1
star
44

divine-font

An icon font for divine-player
JavaScript
1
star
45

fourcrawl

#foursquarehackday2013
Java
1
star
46

emoji-trie

WIP
JavaScript
1
star
47

alexa-response

Build JSON responses for Amazon Alexa, easily.
JavaScript
1
star
48

chancejs-twitter

ChanceJS mixins for Twitter structures.
JavaScript
1
star
49

Escalate

Android app that intercepts SMS messages which match a user-defined RegEx and then goes nuts
Java
1
star