index.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. 'use strict';
  2. const path = require('path');
  3. const writeJsonFile = require('write-json-file');
  4. const sortKeys = require('sort-keys');
  5. const dependencyKeys = new Set([
  6. 'dependencies',
  7. 'devDependencies',
  8. 'optionalDependencies',
  9. 'peerDependencies'
  10. ]);
  11. function normalize(packageJson) {
  12. const result = {};
  13. for (const key of Object.keys(packageJson)) {
  14. if (!dependencyKeys.has(key)) {
  15. result[key] = packageJson[key];
  16. } else if (Object.keys(packageJson[key]).length !== 0) {
  17. result[key] = sortKeys(packageJson[key]);
  18. }
  19. }
  20. return result;
  21. }
  22. module.exports = async (filePath, data, options) => {
  23. if (typeof filePath !== 'string') {
  24. options = data;
  25. data = filePath;
  26. filePath = '.';
  27. }
  28. options = {
  29. normalize: true,
  30. ...options,
  31. detectIndent: true
  32. };
  33. filePath = path.basename(filePath) === 'package.json' ? filePath : path.join(filePath, 'package.json');
  34. data = options.normalize ? normalize(data) : data;
  35. return writeJsonFile(filePath, data, options);
  36. };
  37. module.exports.sync = (filePath, data, options) => {
  38. if (typeof filePath !== 'string') {
  39. options = data;
  40. data = filePath;
  41. filePath = '.';
  42. }
  43. options = {
  44. normalize: true,
  45. ...options,
  46. detectIndent: true
  47. };
  48. filePath = path.basename(filePath) === 'package.json' ? filePath : path.join(filePath, 'package.json');
  49. data = options.normalize ? normalize(data) : data;
  50. writeJsonFile.sync(filePath, data, options);
  51. };