Have you ever run git diff to review your recent code changes, only to be overwhelmed by thousands of modified lines in package-lock.json or bun.lock? It’s like trying to find a specific book on your desk but it’s buried under a mountain of scrap paper.
In this post, we’ll explore how to make Git “ignore” the detailed contents of these files when comparing changes!
The Problem with Lock Files#
When working with package managers like npm, yarn, pnpm, or bun, they generate a “lock file”. This file precisely records the versions of all libraries your project depends on.
[!NOTE] The purpose of a lock file is to guarantee that anyone who clones the project installs the exact same dependencies, preventing the classic “it works on my machine” issue.
The problem arises when you install or update a single library; the lock file can change by hundreds or thousands of lines. When you type git diff, these changes drown out the actual modifications in your source code, making code reviews difficult.
The Solution: Using .gitattributes#
The simplest and most effective way to hide lock file contents is by using .gitattributes. This configuration tells Git: “Hey, I know this file changed, but please don’t print out the detailed line-by-line comparison!”.
Configuring .gitattributes#
Step 1: Create or open the .gitattributes file at the root of your project.
Step 2: Add the following line to the file:
*.lock -difftextOr, if you prefer to specify exact file names:
package-lock.json -diff
bun.lockb -diff
bun.lock -diff
composer.lock -difftextStep 3: Save the file. The -diff attribute instructs Git not to generate a diff for these files when they are modified.
[!TIP] You will still see the lock files listed as “modified” when you run
git status, but their detailed contents will be hidden ingit diff.
Hiding Directly via Command Line#
If you prefer not to modify .gitattributes, you can exclude files directly within the git diff command:
git diff -- . ':(exclude)*.lock'bashTo avoid typing this long command repeatedly, you can create a concise alias in your ~/.gitconfig file:
[alias]
d = diff -- . ':(exclude)*.lock'iniNow, you simply type git d to view your changes without the noise of lock files!