This PR updates our app/lib generators such that `package.json` files
generated have fields in idiomatic order.
e.g.
```json
{
"name": "...",
"version": "...",
"private": true,
"type": "module",
"main": "...",
...
"dependencies": { ... }
}
```
The import fields such as name, version, private, and type are at the
top. Dep fields that could be noisy are at the bottom.
## Current Behavior
<!-- This is the behavior we have today -->
## Expected Behavior
<!-- This is the behavior we should expect with the changes in this PR
-->
## Related Issue(s)
<!-- Please link the issue being fixed so it gets closed when this is
merged. -->
Fixes #
42 lines
1.1 KiB
TypeScript
42 lines
1.1 KiB
TypeScript
import { joinPathFragments, updateJson, type Tree } from '@nx/devkit';
|
|
|
|
export function sortPackageJsonFields(tree: Tree, projectRoot: string) {
|
|
const packageJsonPath = joinPathFragments(projectRoot, 'package.json');
|
|
if (!tree.exists(packageJsonPath)) return;
|
|
updateJson(tree, packageJsonPath, (json) => {
|
|
// Note that these are fields that our generators may use, so it's not exhaustive.
|
|
const orderedTopFields = new Set([
|
|
'name',
|
|
'version',
|
|
'private',
|
|
'description',
|
|
'type',
|
|
'main',
|
|
'module',
|
|
'types',
|
|
'exported',
|
|
]);
|
|
const orderedBottomFields = new Set([
|
|
'dependencies',
|
|
'devDependencies',
|
|
'peerDependencies',
|
|
'optionalDependencies',
|
|
]);
|
|
const otherFields = new Set(
|
|
Object.keys(json).filter(
|
|
(k) => !orderedTopFields.has(k) && !orderedBottomFields.has(k)
|
|
)
|
|
);
|
|
const allFields = [
|
|
...orderedTopFields,
|
|
...otherFields,
|
|
...orderedBottomFields,
|
|
];
|
|
const sortedJson = {};
|
|
for (const k of allFields) {
|
|
sortedJson[k] = json[k];
|
|
}
|
|
return sortedJson;
|
|
});
|
|
}
|