Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@npmcli/package-json

npm27.4mISC6.1.1TypeScript support: definitely-typed

Programmatic API to update package.json

npm, oss

readme

@npmcli/package-json

npm version Build Status

Programmatic API to update package.json files. Updates and saves files the same way the npm cli handles them.

Install

npm install @npmcli/package-json

Usage:

const PackageJson = require('@npmcli/package-json')
const pkgJson = await PackageJson.load(path)
// $ cat package.json
// {
//   "name": "foo",
//   "version": "1.0.0",
//   "dependencies": {
//     "a": "^1.0.0",
//     "abbrev": "^1.1.1"
//   }
// }

pkgJson.update({
  dependencies: {
    a: '^1.0.0',
    b: '^1.2.3',
  },
  workspaces: [
    './new-workspace',
  ],
})

await pkgJson.save()
// $ cat package.json
// {
//   "name": "foo",
//   "version": "1.0.0",
//   "dependencies": {
//     "a": "^1.0.0",
//     "b": "^1.2.3"
//   },
//   "workspaces": [
//     "./new-workspace"
//   ]
// }

There is also a helper function exported for opening a package.json file with no extra normalization or saving functionality.

const { readPackage } = require('@npmcli/package-json/lib/read-package')
const rawData = await readPackage('./package.json')
// rawData will now have the package.json contents with no changes or normalizations

API:

constructor()

Creates a new empty instance of PackageJson.


async PackageJson.create(path)

Creates an empty package.json at the given path. If one already exists it will be overwritten.


async PackageJson.load(path, opts = {})

Loads a package.json at the given path.

  • opts: Object can contain:
    • create: Boolean if true, a new package.json will be created if one does not already exist. Will not clobber ane existing package.json that can not be parsed.

Example:

Loads contents of a package.json file located at ./:

const PackageJson = require('@npmcli/package-json')
const pkgJson = new PackageJson()
await pkgJson.load('./')

Throws an error in case a package.json file is missing or has invalid contents.


static async PackageJson.load(path)

Convenience static method that returns a new instance and loads the contents of a package.json file from that location.

  • path: String that points to the folder from where to read the package.json from

Example:

Loads contents of a package.json file located at ./:

const PackageJson = require('@npmcli/package-json')
const pkgJson = await PackageJson.load('./')

async PackageJson.normalize()

Intended for normalizing package.json files in a node_modules tree. Some light normalization is done to ensure that it is ready for use in @npmcli/arborist

  • path: String that points to the folder from where to read the package.json from
  • opts: Object can contain:
    • strict: Boolean enables optional strict mode when applying the normalizeData step
    • steps: Array optional normalization steps that will be applied to the package.json file, replacing the default steps
    • root: Path optional git root to provide when applying the gitHead step
    • changes: Array if provided, a message about each change that was made to the packument will be added to this array

static async PackageJson.normalize(path, opts = {})

Convenience static that calls load before calling normalize

  • path: String that points to the folder from where to read the package.json from
  • opts: Object can contain:
    • strict: Boolean enables optional strict mode when applying the normalizeData step
    • steps: Array optional normalization steps that will be applied to the package.json file, replacing the default steps
    • root: Path optional git root to provide when applying the gitHead step
    • changes: Array if provided, a message about each change that was made to the packument will be added to this array

async PackageJson.prepare()

Like normalize but intended for preparing package.json files for publish.


static async PackageJson.prepare(path, opts = {})

Convenience static that calls load before calling prepare

  • path: String that points to the folder from where to read the package.json from
  • opts: Object can contain:
    • strict: Boolean enables optional strict mode when applying the normalizeData step
    • steps: Array optional normalization steps that will be applied to the package.json file, replacing the default steps
    • root: Path optional git root to provide when applying the gitHead step
    • changes: Array if provided, a message about each change that was made to the packument will be added to this array

async PackageJson.fix()

Like normalize but intended for the npm pkg fix command.


PackageJson.update(content)

Updates the contents of a package.json with the content provided.

  • content: Object containing the properties to be updated/replaced in the package.json file.

Special properties like dependencies, devDependencies, optionalDependencies, peerDependencies will have special logic to handle the update of these options, such as sorting and deduplication.

Example:

Adds a new script named new-script to your package.json scripts property:

const PackageJson = require('@npmcli/package-json')
const pkgJson = await PackageJson.load('./')
pkgJson.update({
  scripts: {
    ...pkgJson.content.scripts,
    'new-script': 'echo "Bom dia!"'
  }
})

NOTE: When working with dependencies, it's important to provide values for all known dependency types as the update logic has some interdependence in between these properties.

Example:

A safe way to add a devDependency AND remove all peer dependencies of an existing package.json:

const PackageJson = require('@npmcli/package-json')
const pkgJson = await PackageJson.load('./')
pkgJson.update({
  dependencies: pkgJson.content.dependencies,
  devDependencies: {
    ...pkgJson.content.devDependencies,
    foo: '^foo@1.0.0',
  },
  peerDependencies: {},
  optionalDependencies: pkgJson.content.optionalDependencies,
})

get PackageJson.content

Getter that retrieves the normalized Object read from the loaded package.json file.

Example:

const PackageJson = require('@npmcli/package-json')
const pkgJson = await PackageJson.load('./')
pkgJson.content
// -> {
//   name: 'foo',
//   version: '1.0.0'
// }

async PackageJson.save()

Saves the current content to the same location used when calling load().

LICENSE

ISC

changelog

Changelog

6.1.1 (2025-01-21)

Bug Fixes

6.1.0 (2024-11-27)

Features

  • 4c22738 #133 adds ability to sort package.json on save (#133) (@reggi, @wraithgar)

    Chores

  • 6fef3a2 #135 bump @npmcli/template-oss from 4.23.3 to 4.23.5 (#135) (@dependabot[bot], @npm-cli-bot)

6.0.1 (2024-10-02)

Dependencies

6.0.0 (2024-09-26)

⚠️ BREAKING CHANGES

5.2.1 (2024-09-17)

Bug Fixes

  • 962b9e1 #119 hidden dir path clean up corrected (#119) (@milaninfy)

    Chores

  • e26e236 #118 postinstall for dependabot template-oss PR (@hashtagchris)
  • 8a7714b #118 bump @npmcli/template-oss from 4.23.1 to 4.23.3 (@dependabot[bot])

5.2.0 (2024-06-03)

Features

  • 62e585a #106 add readPackage helper (#106) (@wraithgar)

5.1.1 (2024-05-28)

Bug Fixes

  • 54756d2 #105 apply securePath to package bin (#105) (@antongolub)
  • 46c563b add normalizePackageMan helper (#100) (@antongolub)
  • a974274 prevent directory.man referencing outside the package root (#104) (@antongolub)
  • 191b521 #102 invalid scripts warning fixed for undefined scripts (#102) (@milaninfy)

Chores

  • 45a2937 #98 bump @npmcli/template-oss to 4.22.0 (@lukekarrys)
  • 90863c1 #98 postinstall for dependabot template-oss PR (@lukekarrys)

5.1.0 (2024-04-22)

Features

  • 17788d0 #96 add fromContent method to set contents directly (#96) (@lukekarrys)

Chores

  • 9597b84 #94 postinstall for dependabot template-oss PR (@lukekarrys)
  • 5e20e64 #94 bump @npmcli/template-oss from 4.21.3 to 4.21.4 (@dependabot[bot])

5.0.3 (2024-04-12)

Dependencies

5.0.2 (2024-04-10)

Bug Fixes

  • a67317b #90 perf: lazy load hosted git info on normalize (#90) (@H4ad)
  • 06df698 #89 perf: lazy load glob on normalize.js (#89) (@H4ad)

5.0.1 (2024-04-07)

Bug Fixes

  • fda5722 #87 perf: lazy load un-common dependencies for npm run (#87) (@H4ad)
  • 71f09d6 #88 perf: only import necessary functions from semver (#88) (@H4ad)

Documentation

  • 6ebb3c9 #85 readme: fix broken badge URL (#85) (@10xLaCroixDrinker)

Chores

  • 66e0c23 #80 postinstall for dependabot template-oss PR (@lukekarrys)
  • 00e4bbb #80 bump @npmcli/template-oss from 4.21.1 to 4.21.3 (@dependabot[bot])
  • d784aa8 #77 postinstall for dependabot template-oss PR (@lukekarrys)
  • efeee22 #77 bump @npmcli/template-oss from 4.19.0 to 4.21.1 (@dependabot[bot])
  • a4df4cf #56 bump read-package-json from 6.0.4 to 7.0.0 (@dependabot[bot])
  • f7c048a #58 postinstall for dependabot template-oss PR (@lukekarrys)
  • 6240313 #58 bump @npmcli/template-oss from 4.18.1 to 4.19.0 (@dependabot[bot])
  • 5ab117c #57 postinstall for dependabot template-oss PR (@lukekarrys)
  • f56390e #57 bump @npmcli/template-oss from 4.18.0 to 4.18.1 (@dependabot[bot])

5.0.0 (2023-08-15)

⚠️ BREAKING CHANGES

  • support for node 14 has been removed

Bug Fixes

Dependencies

  • f08b79e #55 bump normalize-package-data from 5.0.0 to 6.0.0
  • 5c4de21 #52 bump hosted-git-info from 6.1.1 to 7.0.0
  • 02e0ef2 #51 bump @npmcli/git from 4.1.0 to 5.0.0

4.0.1 (2023-07-17)

Bug Fixes

  • 04bc9cf #49 don't report node_modules/.bin fix unless it happened (@wraithgar)
  • 3c1cb66 #49 inline bin normalization code (@wraithgar)
  • e97e423 #48 properly parse strict flag on version check (#48) (@wraithgar)
  • 3bcf2fd #47 only report bundleDependencies change if it was changed (@wraithgar)
  • 09d8573 #47 pull in fix logic from normalize-package-data (@wraithgar)
  • 60a09da #44 check for changes array during author step (#44) (@wraithgar)

Dependencies

4.0.0 (2023-07-05)

⚠️ BREAKING CHANGES

  • the path parameter is now tied to load and not the class constructor.

Features

  • e2bc4f3 #43 add fix method (@wraithgar)
  • 7ddb1d1 #41 add changes array to normalize functions (#41) (@wraithgar)
  • 4775bf3 add create functionality (@wraithgar)

Bug Fixes

  • ed68a28 #43 typo in changes message (@wraithgar)
  • c3d11c2 move path parameter to load (@wraithgar)

3.1.1 (2023-06-06)

Bug Fixes

  • 9e0859b #36 make prepare and normalize have feature parity with legacy packages (@lukekarrys)

Dependencies

3.1.0 (2023-05-15)

Features

Dependencies

3.0.0 (2022-10-12)

⚠️ BREAKING CHANGES

  • @npmcli/package-json is now compatible with the following semver range for node: ^14.17.0 || ^16.13.0 || >=18.0.0

Features

  • 7617680 #10 postinstall for dependabot template-oss PR (@lukekarrys)

Dependencies

  • 391bcb4 #17 bump json-parse-even-better-errors from 2.3.1 to 3.0.0

2.0.0 (2022-04-05)

⚠ BREAKING CHANGES

  • this drops support for node10 and non-LTS versions of node 12 and node 14

Documentation

Dependencies