Google Sheets iconSwift icon
Published at
Updated at
Reading time
2min

This post initially described the npm-diff package's functionality and was updated after npm shipped an integrated diff command.

The release of npm v7.5.0 includes a new command – npm diff. The npm documentation describes the command as follows:

Similar to its git diff counterpart, this command will print diff patches of files for packages published to the npm registry.

You probably know the situation: you update one dependency in your Node.js project and everything breaks. Even though this update was supposed to be a backwards-compatible patch release, things went down and you're in "dependency update hell".

How can you then create a diff of the updated npm packages quickly? Should you go to GitHub and make a diff there? I always felt lost in this situation and didn't have a great workflow.

This situation is where the npm diff command comes into play. 🎉

Use npm diff to find out what changed quickly. Define the package name paired with two release version numbers, and you can access a diff of the two package versions.

npm diff --diff=<spec-a> --diff=<spec-b>

# example:
npm diff --diff=web-vitals-element@1.0.0 --diff=web-vitals-element@1.0.1

Colorful diff using npm diff

The command prints a colourful diff to the terminal. That by itself is very useful already. When I dive into long diffs, I prefer two other features:

  • proper syntax highlighting
  • side-by-side file comparison

How can you integrate these two features?

Meet delta – a diff tool with syntax highlighting

A while ago, I started using delta for git diffs on the command line. It's fantastic! It shows line numbers, supports syntax highlighting and is highly configurable. It even supports side-by-side diffing in the terminal!

You can run the following command:

npm diff --diff=web-vitals-element@1.0.0 --diff=web-vitals-element@1.0.1 | delta --width $(tput cols) --side-by-side | less

npm diff command piped into delta and less

That looks pretty great if you ask me!

npm diff's output is piped into delta. side-by-side enables the two-column comparison and --width $(tput cols) defines the side-by-side comparison's width as terminal window width. And lastly, everything is piped into less because I'm used to navigating files with it.

This command fits nicely into my workflow, but it's a lot to type. Let's improve the convenience by defining a custom shell function.

A custom npm diff function in my dotfiles

My own npm-diff is way shorter and easier to type. 🎉

# example: 
#   npm-diff web-vitals-element 1.0.0 1.0.1
function npm-diff() {
  npm diff --diff=$1@$2 --diff=$1@$3 | delta --width $(tput cols) | less
}

Happy diffing! 👋

If you want to learn more things about npm and Node.js, make sure to look at my blog's "Today I learned" section or subscribe to my weekly web development newsletter.

Related Topics

Related Articles