Skip to content

[Bug]: yarn@v4 install Rewrites package.json when it shouldn't, stripping blank lines & failing to execute postinstall when it should #6844

@fbartho

Description

@fbartho

Self-service

  • I'd be willing to implement a fix

Describe the bug

Originally raised as a discussion in 2021 it's definitively a bug, or it should be documented somewhere that yarn is always willing to rewrite your package.json, even if no logical changes occurred.

  1. yarn install will call a script called postinstall on first install. This allows devs to hook in custom tooling.
  2. But, if no dependency changes occurred (eg. changes to node_modules or other caches), it will skip calling postinstall -- presumably as an optimization.
  3. 🐛 Executing yarn has a side effect of rewriting your package.json, it strips newlines, and has some other purpose.
  4. The optimization from 2 and the unwanted side-effect from 3 means your custom tooling cannot guarantee to be executed to ensure your package.json is formatted the way your repo demands.

A user workaround exists by installing a custom plugin in .yarnrc.yml (endorsed on yarn's plugin page), and hooking your postinstall script into that. But that's a performance deoptimization, and gross. Why should yarn endorse a workaround to unwanted features?

To reproduce

.prettierignore

package.json

package.json:

{
	"scripts": {
		"postinstall": "touch postinstall-side-effect.log"
	},

	"packageManager": "yarn@4.6.0",

	"license": "UNLICENSED"
}
  1. yarn install -- creates .pnp.cjs, .yarn/*, yarn.lock as well as postinstall-side-effect.log -- it also rewrites package.json stripping the blank lines.
  2. reset the package.json to the above, and delete postinstall-side-effect.log
  3. yarn install -- this rewrites package.json stripping the blank lines, and does nothing else

Expected behavior:

A. It should not rewrite my package.json. Blank lines are not illegal, no logical changes occurred.
B. I have a postinstall script, and I told it yarn install. It should execute my postinstall script.

Yarn should not introduce unwanted formatting side-effects. Yarn should respect standard script hooks.

Environment

System:
    OS: macOS 15.5
    CPU: (10) arm64 Apple M1 Max
  Binaries:
    Node: 23.6.0 - /private/var/folders/01/4rfqmhmn03s0vby9xw8cz6qr0000gp/T/xfs-33b4dbe9/node
    Yarn: 4.6.0 - /private/var/folders/01/4rfqmhmn03s0vby9xw8cz6qr0000gp/T/xfs-33b4dbe9/yarn
    npm: 10.9.2 - ~/.nvm/versions/node/v23.6.0/bin/npm

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions