Skip to content

Commit

Permalink
feat: allow custom ordering of package.json properties (#55)
Browse files Browse the repository at this point in the history
  • Loading branch information
amilajack authored and keithamus committed Feb 4, 2019
1 parent ab11868 commit 28e5558
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
5 changes: 3 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,8 @@ const defaultNpmScripts = [
'version'
];

function sortPackageJson(packageJson) {
function sortPackageJson(packageJson, options = {}) {
const determinedSortOrder = options.sortOrder || sortOrder;
let wasString = false;
let endCharacters = '';
let indentLevel = 2;
Expand Down Expand Up @@ -179,7 +180,7 @@ function sortPackageJson(packageJson) {
sortSubKey('preferGlobal');
sortSubKey('private');
sortSubKey('publishConfig');
packageJson = sortObjectKeys(packageJson, sortOrder);
packageJson = sortObjectKeys(packageJson, determinedSortOrder);
return wasString
? JSON.stringify(packageJson, null, indentLevel) + endCharacters
: packageJson;
Expand Down
19 changes: 19 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,24 @@ fs.readFile('./package.json', 'utf8', (error, contents) => {
]
);

// Custom sort order
assert.deepEqual(
Object.keys(
sortPackageJson(
{
scripts: {
name: 'my-package',
engines: '>=10'
}
},
{
sortOrder: ['engines', 'name']
}
).scripts
),
['engines', 'name']
);

assert.equal(sortPackageJson('{}\n'), '{}\n');
assert.equal(sortPackageJson('{"foo":"bar"}\n'), '{"foo":"bar"}\n');

Expand All @@ -88,3 +106,4 @@ fs.readFile('./package.json', 'utf8', (error, contents) => {
'{\n "name": "foo",\n "version": "1.0.0"\n}'
);
});

0 comments on commit 28e5558

Please sign in to comment.