npm add -D format-package "prettier@^2.0.0 || ^3.0.0"Table of Contents
package.json files are notorious for becoming large and overwhelming. When working in teams, this can make it hard to know how to structure the file or where to find certain configurations or scripts - especially since everyone has their own preferences.
And manually going through and organizing the file seems as painful as doing formatting checks by hand in PRs.
format-package solves these problems by allowing the file to be sorted and formatted in a consistent and automated manner.
It is configurable to allow teams to pick the order that work best for them, and includes transformations that can be applied to a value in the package.json (such as logically sorting scripts).
- node: >=22.18.0
This module provides a simple CLI that can be run directly or with npx:
./node_modules/.bin/format-package --help
# or
npx format-package --helpIt can also be used as part of an npm script:
{
"scripts": {
"format:pkg": "format-package -w"
},
"devDependencies": {
"format-package": "latest"
}
}npm run format:pkgThe module exports an asynchronous format function that takes the contents of package.json and a set of options.
It returns a newly sorted and formatted package.json string.
#!/usr/bin/env node
import { writeFile } from 'node:fs/promises';
import format from 'format-package';
import pkg from '<path-to-package.json>' with { type: 'json' };
const formatPackage = async (pkg, filePath) => {
const formattedPkg = await format(pkg, options);
await writeFile(filePath, formattedPkg, 'utf8');
};
formatPackage(pkg).catch((error) => {
console.error(error);
process.exit(1);
});There are three options:
- order (Array)
- transformations (Object)
- formatter (Function)
Options are expected to be passed in as a keyed object:
import format from 'format-package';
import pkg from '<path-to-package.json>' with { type: 'json' };
const options = {
order: [],
transformations: {},
formatter: (pkg) => pkg.toString(),
};
format(pkg, options).then((formattedPkg) => console.log(formattedPkg));The format-package module also exports its defaults to help with configuration:
import format from 'format-package';
import pkg from '<path-to-package.json>' with { type: 'json' };
const {
defaults: { order: defaultOrder },
} = format;
// Move `...rest` to the bottom of the default order list
const restIndex = defaultOrder.indexOf(sort, '...rest');
let order = [...defaultOrder];
if (restIndex !== -1) {
order.splice(restIndex, 1);
}
order.push('...rest');
format(pkg, {
order,
}).then((formattedPkg) => console.log(formattedPkg));The most meaningful part of this utility is an ordered array of keys that are used to order the contents of package.json.
The default order is:
[
"name",
"version",
"description",
"license",
"private",
"engines",
"os",
"cpu",
"repository",
"bugs",
"homepage",
"author",
"contributors",
"keywords",
"bin",
"man",
"type",
"main",
"exports",
"module",
"browser",
"files",
"directories",
"workspaces",
"config",
"publishConfig",
"scripts",
"husky",
"lint-staged",
"...rest",
"dependencies",
"peerDependencies",
"devDependencies",
"optionalDependencies",
"bundledDependencies"
]The ...rest value is considered special. It marks the location where the remaining package.json keys that are not found in this ordered list will be placed in alphabetical order.
Note: if a ...rest string is not found in the provided order list, it will be appended to the bottom.
import format from 'format-package';
import pkg from '<path-to-package.json>' with { type: 'json' };
const options = {
order: [
'name',
'version',
'scripts',
'jest',
'dependencies',
'peerDependencies',
'devDependencies',
'optionalDependencies',
'...rest',
],
};
format(pkg, options).then((formattedPkg) =>
Object.keys(JSON.parse(formattedPkg))
);
/*
[ 'name',
'version',
'scripts',
'dependencies',
'devDependencies',
'optionalDependencies',
'author',
'bin',
'bugs',
'description',
'engines',
'homepage',
'license',
'lint-staged',
'main',
'repository' ]
*/transformations is a map of package.json keys and corresponding synchronous or asynchronous functions that take a key and value and return a key and value to be written to package.json.
The default transformations map has:
scriptsfunction that sorts the scripts in a sensical way using 'sort-scripts'exportsfunction that ensures the ordering remains the same*function that sorts the value alphabetically if possible
import sortScripts from 'sort-scripts';
import type { Transformations } from '../../types.ts';
import { alphabetize } from '../../utils/object.ts';
const transformations: Transformations = {
scripts(key, prevValue) {
const nextValue = sortScripts(prevValue).reduce(
(obj, [name, value]) => ({ ...obj, [name]: value }),
{}
);
return [key, nextValue];
},
// Order of exports keys matters
// https://github.com/camacho/format-package/issues/116
exports: (key, prevValue) => [key, prevValue],
// Special case for all keys without defined transforms
'*': (key, value) => [key, alphabetize(value)],
};
export default transformations;The * value is considered special. It is the function that will be used for package.json keys that are not found.
Note: Any package.json property that is an object and does not have a defined transformation will use the * transformation function. If a * default function is not defined, alphabetize will be used.
Additional transformations or overrides can be passed in:
import format from 'format-package';
import pkg from '<path-to-package.json>' with { type: 'json' };
const options = {
transformations: {
// This reverses all the keys in dependencies
dependencies(key, value) {
return [
key,
Object.keys(value)
.sort()
.reverse()
.reduce((obj, k) => {
obj[k] = value[k];
return obj;
}, {}),
];
},
},
};
format(pkg, options);The formatter is the function used to prepare the contents before being returned.
A custom synchronous or asynchronous formatter can be supplied that will process the resulting package contents.
By default, the formatter will try to use prettier if it is installed, and will fallback to JSON.stringify if the peer dependency is not found:
import path from 'path';
import type { Formatter } from '../../types.ts';
const formatter: Formatter = async (obj, filePath) => {
const content = JSON.stringify(obj, null, 2);
// Try to use prettier if it can be imported,
// otherwise add a new line at the end
let prettierMod;
try {
prettierMod = await import('prettier');
} catch {
return `${content}\n`;
}
// prettier@2 is CJS; under ESM the callable API lands on .default. The
// fallback covers a pure-ESM prettier with no default export.
/* v8 ignore next -- defensive interop fallback */
const prettier = prettierMod.default ?? prettierMod;
let config = await prettier.resolveConfig(
filePath ? path.dirname(filePath) : process.cwd()
);
if (!config) {
config = {};
}
return prettier.format(content, {
...config,
parser: 'json',
printWidth: 0,
});
};
export default formatter;The CLI accepts a series of files or globs to be formatted, as well as a set of options.
npx format-package "**/package.json"Options can also be passed as environment variables and are used in the following order of precedence:
- Command line options
- Env vars
FORMAT_PACKAGE_VERBOSE=true| Option | Alias | ENV | Description | Default |
|---|---|---|---|---|
config |
c |
FORMAT_PACKAGE_CONFIG |
Path to a custom configuration to use. This configuration can be JavaScript, JSON, or any other format that your configuration of node can require. The default configuration can be found here. |
|
write |
w |
FORMAT_PACKAGE_WRITE |
Write the output to the location of the found package.json |
false |
ignore |
i |
FORMAT_PACKAGE_IGNORE |
Patterns for ignoring matching files | ['**/node_modules/**'] |
verbose |
v |
FORMAT_PACKAGE_VERBOSE |
Print the output of the formatting | false |
help |
h |
Print help menu |
You can also see the available options in the terminal by running:
npx format-package --helpformat-package will search for a valid configuration file in the following order of precedence.
-
If the option
--config [path | module id]or aFORMAT_PACKAGE_CONFIGenvironment variable is provided:a. check if the value resolves to a module id, else b. check if value resolves to an existing pathIf either
aorbare valid configuration, then use the configuration, else return the default configuration.
If neither a --config or a FORMAT_PACKAGE_CONFIG environment variable is provided, search for configurations in the following places:
format-package.jsformat-package.yamlorformat-package.ymlformat-package.jsonformat-package.config.jsformat-package.config.yamlorformat-package.config.ymlformat-packageproperty inpackage.json
If there are no configuration from the above search places, format-package will move up one directory level and try again.
format-package will continue searching until arriving at the home directory.
If no configuration is found, then the default configuration is used.
const JoiConfigSchema = Joi.object({
order: Joi.array().min(1).unique().optional(),
transformations: Joi.object().optional(),
formatter: Joi.function().optional(),
});Supported configuration formats: JSON, JSON5, JS, and YAML.
{
"order": ["name", "version"]
}{
"order": ["name", "description", "..."]
}module.exports = {
order: ['name', 'description', '...'],
};order:
- name
- description
- ...An effective integration of this plugin could look like this:
.husky/pre-commit:
npx lint-stagedpackage.json:
{
"scripts": {
"format:pkg": "format-package -w",
"prepare": "husky"
},
"lint-staged": {
"package.json": ["format-package -w"]
},
"devDependencies": {
"format-package": "latest",
"husky": "latest",
"lint-staged": "latest"
}
}This configuration combines:
- lint-staged for automatically running tasks on staged files
- husky for githook integrations
- format-package to format
package.json
Together, they ensure the package.json file is automatically formatted if it changes and provides an easy package.json script for manual use:
npm run format:pkgClone the repo and install dependencies to get started with development:
git clone git@github.com:camacho/format-package.git
npm installThese scripts can be run via npm run:
| Script | Description |
|---|---|
prebuild |
clean the dist directory to prevent dangling artifacts |
build |
transpile TypeScript files in the src directory into JavaScript files in the dist directory |
postbuild |
make dist/cli/index.js file executable |
dev |
run src/cli/index.ts directly with node (native TypeScript) |
docs |
update auto-generated-content blocks in Markdown files |
format |
format application code |
gamut |
run the full gamut of checks - reset environment, generate docs, format and lint code, run tests, and build |
lint |
lint the application code |
prepack |
build the package before it is packed for npm pack or npm publish |
prepare |
husky |
prepublishOnly |
make sure the package is in good state before publishing |
reset |
clean dist directory and reset the node_modules dependencies |
start |
run the cli from dist directory |
test |
run tests for the application |
type-check |
check repository types |
watch |
run node --watch on src/cli/index.ts for live reload |
Note - This repo depends on husky and lint-staged to automatically format code and update documents. If these commands are not run, code changes will most likely fail.