![Create React App Officially Deprecated Amid React 19 Compatibility Issues](https://cdn.sanity.io/images/cgdhsj6q/production/04fa08cf844d798abc0e1a6391c129363cc7e2ab-1024x1024.webp?w=400&fit=max&auto=format)
Security News
Create React App Officially Deprecated Amid React 19 Compatibility Issues
Create React App is officially deprecated due to React 19 issues and lack of maintenance—developers should switch to Vite or other modern alternatives.
format-package
Advanced tools
yarn add -D format-package prettier@^1.6.0
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).
This module provides a simple CLI:
./node_modules/.bin/format-package --help
If combined with Yarn, it can be run as:
yarn format-package --help
It can also be used as part of an npm script:
{
"scripts": {
"format:pkg": "format-package -w"
},
"devDependencies": {
"format-package": "latest"
}
}
yarn format:pkg
The 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
const fs = require('fs');
const format = require('format-package');
const pkg = require('<path-to-package.json>');
async function formatPackage(pkg) {
const formattedPkg = await format(pkg, options);
fs.writeFile('<path-to-package.json>', formattedPkg, err => {
if (err) throw err;
});
}
formatPackage(pkg).catch(err => {
console.error(err);
process.exit(1);
});
There are three options:
Options are expected to be passed in as a keyed object:
const format = require('format-package');
const pkg = require('<path-to-package.json>');
const options = {
order: [],
transformations: {},
formatter: v => v.toString(),
};
format(pkg, options).then(formattedPkg => console.log(formattedPkg));
The format-package
module also exports its defaults to help with configuration:
const format = require('format-package');
const pkg = require('<path-to-package.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));
order
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",
"keywords",
"bin",
"man",
"main",
"module",
"browser",
"files",
"directories",
"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.
const format = require('format-package');
const pkg = require('<path-to-package.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
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 a scripts
method that sorts the scripts in a sensical way using 'sort-scripts'.
const sortScripts = require('sort-scripts');
const transformations = {
scripts(key, prevValue) {
const nextValue = sortScripts(prevValue).reduce(
(obj, [name, value]) => Object.assign({}, obj, { [name]: value }),
{}
);
return [key, nextValue];
},
};
module.exports = transformations;
Notes: Any package.json
property that is an object and does not have a defined transformation will be alphabetically sorted.
Additional transformations or overrides can be passed in:
const format = require('format-package');
const pkg = require('<path-to-package.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);
formatter
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:
async function formatter(obj) {
const content = JSON.stringify(obj, null, 2);
let prettier;
try {
prettier = require('prettier');
} catch (error) {
return [content, '\n'].join('');
}
const options = (await prettier.resolveConfig(process.cwd())) || {};
return prettier.format(content, {
...options,
parser: 'json',
printWidth: 0,
});
}
module.exports = formatter;
The CLI accepts a series of files or globs to be formatted, as well as a set of options.
yarn format-package "**/package.json"
Options can also be passed as environment variables and are used in the following order of precedence:
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:
yarn format-package --help
format-package
will search for a valid configuration file in the following order of precedence.
If the option --config [path | module id]
or a FORMAT_PACKAGE_CONFIG
environment variable is provided:
a. check if the value resolves to a module id, else
b. check if value resolves to an existing path
If either a
or b
are valid configuration, then use the configuration, else continue searching.
format-package
property in package.json
If there are no valid configuration, it will use the default.
const JoiConfigSchema = Joi.object({
order: Joi.array()
.min(0)
.unique(),
transformations: Joi.object().optional(),
formatter: Joi.func().optional(),
});
Supported configuration formats: JSON, JSON5, JS, and YAML.
{
"order": ["name", "version"]
}
{
"order": ["name", "description", "..."]
}
format-package.js
or format-package.config.js
module.exports = {
order: ['name', 'description', '...'],
};
order:
- name
- description
- ...
An effective integration of this plugin could look like this:
{
"scripts": {
"format:pkg": "format-package -w",
"precommit": "lint-staged",
"prepublish": "format:pkg"
},
"lint-staged": {
"package.json": ["format-package -w", "git add"]
},
"devDependencies": {
"lint-staged": "latest",
"format-package": "latest"
},
"optionalDependencies": {
"husky": "latest"
}
}
This configuration combines:
package.json
Together, these modules ensure the package.json
file is automatically formatted if it changes and provides an easy package.json script for manual use:
yarn format:pkg
Clone the repo and install dependencies to get started with development:
git clone git@github.com:camacho/format-package.git
yarn install
These scripts can be run via yarn
or npm run
:
Script | Description |
---|---|
docs | updates any auto-generated-content blocks in Markdown files |
format | format the application code |
format:package | ./lib/cli/index.js -w package.json |
format:source | prettier --write "**/*.{md,js,json}" |
gamut | run the full gamut of checks - reset environment, generate docs, format and lint code, and run tests |
lint | lint the application code |
prepublishOnly | make sure the package is in good state before publishing |
reset | reset the node_modules dependencies |
test | run unit tests for the application |
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.
FAQs
Sensible formatting and ordering of package.json
The npm package format-package receives a total of 33 weekly downloads. As such, format-package popularity was classified as not popular.
We found that format-package demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Create React App is officially deprecated due to React 19 issues and lack of maintenance—developers should switch to Vite or other modern alternatives.
Security News
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
Security News
The Linux Foundation is warning open source developers that compliance with global sanctions is mandatory, highlighting legal risks and restrictions on contributions.