or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-sort-package-json

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

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/sort-package-json@2.4.x

To install, run

npx @tessl/cli install tessl/npm-sort-package-json@2.4.0

index.mddocs/

Sort Package JSON

Sort Package JSON is a JavaScript utility that sorts package.json files according to well-established conventions. It provides both programmatic API and CLI interfaces for organizing package.json keys in a standardized order, helping maintain consistent project structure across teams and development environments.

Package Information

  • Package Name: sort-package-json
  • Package Type: npm
  • Language: JavaScript (ES Modules)
  • Installation: npm install sort-package-json

Core Imports

import sortPackageJson from "sort-package-json";
import { sortPackageJson, sortOrder } from "sort-package-json";

For CommonJS environments:

const sortPackageJson = require("sort-package-json");
const { sortPackageJson, sortOrder } = require("sort-package-json");

Basic Usage

import sortPackageJson from "sort-package-json";

// Sort a package.json string
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));
// Output: Formatted JSON string with keys in proper order

// Sort a package.json object
const packageJsonObject = JSON.parse(packageJsonString);
const sorted = sortPackageJson(packageJsonObject);
console.log(sorted);
// Output: Object with keys sorted according to conventions

Capabilities

Package JSON Sorting

Main function that sorts package.json content according to well-known field conventions.

/**
 * Sort packageJson object or string according to well-known conventions
 * @param packageJson - Package.json content as string or object
 * @param options - Optional sorting configuration
 * @returns Sorted package.json with same type as input
 */
function sortPackageJson<T extends Record<any, any>>(packageJson: T, options?: Options): T;
function sortPackageJson(packageJson: string, options?: Options): string;

interface Options {
  readonly sortOrder?: readonly string[] | ComparatorFunction;
}

type ComparatorFunction = (left: string, right: string) => number;

Key Features:

  • Dual Input Support: Accepts both JSON strings and JavaScript objects
  • Format Preservation: Maintains original indentation and line endings for string inputs
  • Smart Field Recognition: Recognizes 100+ package.json fields including dependencies, scripts, and tool configurations
  • Custom Sort Orders: Supports custom field ordering via options parameter
  • Type Safety: Full TypeScript support with proper type inference

Usage Examples:

import sortPackageJson from "sort-package-json";

// Basic sorting with string input
const sorted = sortPackageJson('{"version":"1.0.0","name":"test"}');
// Returns: '{"name":"test","version":"1.0.0"}'

// Sorting with object input
const obj = { version: "1.0.0", name: "test", dependencies: {} };
const sortedObj = sortPackageJson(obj);
// Returns object with fields in conventional order

// Custom sort order
const customSorted = sortPackageJson(obj, {
  sortOrder: ['version', 'name'] // version will come before name
});

// Function-based sorting
const funcSorted = sortPackageJson(obj, {
  sortOrder: (left, right) => right.localeCompare(left) // reverse alphabetical
});

Default Sort Order

Array containing the default field ordering used by the sorting function.

/**
 * Default sort order for package.json fields
 * Contains 100+ field names in conventional order
 */
const sortOrder: readonly string[];

The default sort order includes standard fields like:

  1. Metadata: $schema, name, displayName, version, private, description
  2. Repository Info: keywords, homepage, bugs, repository, funding, license
  3. People: author, maintainers, contributors, publisher
  4. Module System: type, exports, main, module, browser, types
  5. Executables: bin, man, directories, files
  6. Scripts: scripts, betterScripts
  7. Dependencies: dependencies, devDependencies, peerDependencies, optionalDependencies
  8. Configuration: engines, volta, config, tool-specific configs (eslint, prettier, etc.)

Usage Example:

import { sortOrder } from "sort-package-json";

console.log(sortOrder.slice(0, 5));
// Output: ['$schema', 'name', 'displayName', 'version', 'stableVersion']

// Use in custom sorting
const customOrder = [...sortOrder, 'myCustomField'];

CLI Interface

The package provides a command-line interface for sorting package.json files directly.

Installation and Basic Usage

# Global installation
npm install -g sort-package-json

# Or use via npx
npx sort-package-json

# Sort specific files
sort-package-json package.json
sort-package-json "packages/*/package.json"

CLI Commands and Options

sort-package-json [options] [file/glob ...]

Options:
  -c, --check     Check if files are sorted (validation mode)
  -q, --quiet     Don't output success messages
  -h, --help      Display help information
  -i, --ignore    An array of glob patterns to ignore (default: ['node_modules/**'])
  -v, --version   Display package version
  --stdin         Read from stdin, output to stdout

Usage Examples:

# Sort current package.json
sort-package-json

# Check if files are sorted
sort-package-json --check
sort-package-json "**/*.json" --check

# Sort multiple files with ignore patterns
sort-package-json "packages/*/package.json" --ignore "packages/legacy/*"

# Use with stdin/stdout
cat package.json | sort-package-json --stdin > sorted-package.json

# Quiet mode (suppress success messages)
sort-package-json --quiet

CLI Exit Codes

The CLI returns different exit codes to indicate various outcomes:

  • 0: Success - all files processed successfully
  • 1: Check mode failed - some files are not sorted (only in --check mode)
  • 2: Error - no matching files found, invalid arguments, or file processing errors

Examples:

# Check if files are sorted (exits with 1 if any are unsorted)
sort-package-json --check
echo $? # Will be 1 if files need sorting

# Successful sorting (exits with 0)
sort-package-json package.json
echo $? # Will be 0 on success

# Error case - no files found (exits with 2)
sort-package-json "nonexistent/*.json"
echo $? # Will be 2

Advanced Configuration

Custom Sort Orders

You can customize the field ordering using the sortOrder option:

import sortPackageJson from "sort-package-json";

// Array-based custom order (fields not listed fall back to default order)
const result = sortPackageJson(packageJson, {
  sortOrder: ['version', 'name'] // version will appear before name
});

// Function-based custom sorting
const result2 = sortPackageJson(packageJson, {
  sortOrder: (left, right) => {
    // Custom comparison logic
    return left.localeCompare(right);
  }
});

Private Field Handling

Fields starting with underscore (_) are treated as private and sorted separately at the end:

const packageJson = {
  name: "test",
  version: "1.0.0", 
  _private: "value",
  _internal: "data"
};

const sorted = sortPackageJson(packageJson);
// Result: name, version, _internal, _private

Format Preservation

For string inputs, the function preserves original formatting:

// Preserves 4-space indentation
const indented = sortPackageJson('{\n    "version": "1.0.0",\n    "name": "test"\n}');

// Preserves tab indentation  
const tabbed = sortPackageJson('{\n\t"version": "1.0.0",\n\t"name": "test"\n}');

// Preserves Windows line endings
const windows = sortPackageJson('{"version":"1.0.0",\r\n"name":"test"}');

Error Handling

The library handles various edge cases gracefully:

  • Invalid JSON: Returns original input unchanged for string inputs
  • Non-object inputs: Arrays and primitive values are returned unchanged
  • Missing fields: Only sorts fields that are present
  • Nested objects: Automatically sorts nested objects in specific fields (dependencies, etc.)

Types

interface Options {
  /** Custom sort order as array of field names or comparison function */
  readonly sortOrder?: readonly string[] | ComparatorFunction;
}

type ComparatorFunction = (left: string, right: string) => number;

interface SortPackageJson {
  /** Sort packageJson object */
  <T extends Record<any, any>>(packageJson: T, options?: Options): T;
  /** Sort packageJson string */
  (packageJson: string, options?: Options): string;
}