Git is an open source distributed version control system. It is currently the most popular version control system according to various surveys, and has been the core driver of many popular development platforms, such as GitHub, GitLab, Bitbucket, etc.

Many JavaScript developers also use Git as their main version control system. Therefore, improving Git experience is key to a productive and happy JavaScript development process.

A Generally Better Git Configuration

Many improvements not specific to JavaScript can be made on top of the default Git configuration. For a better general Git configuration, please check out Unleash Git Power with Enhanced User Configuration.

Untracking Files Using .gitignore

.gitignore, located at the root of the Git repository, specifies files that Git should not track. The GitHub gitignore repository provides a good starting point of .gitignore for a JavaScript project. For convenience, the content is also available below.

Click to show/hide .gitignore

Additionally, also consider adding /*.tar.gz to .gitignore if you are working on an npm package, so that the output of npm pack stays untracked.

No Diff of Lock Files

Lock files include package-lock.json, yarn-lock.json, pnpm-lock.yaml, etc. Generally, they should be tracked by Git. Developers are interested in knowing whether these files have changed. However, the exact diffs, such as those output by commands such as git show and git diff, are usually irrelevant to developers. Hence, we can stop Git from displaying the diffs of these files by adding the lock files to .gitattributes located at the root of the Git repository:

package-lock.json binary
yarn-lock.json binary
pnpm-lock.yaml binary

After making these changes, Git will only show whether the file has changed or not, similar to the following:

diff --git a/package-lock.json b/package-lock.json
index f77c979af1ba..4b8ba602b6e3 100644
Binary files a/package-lock.json and b/package-lock.json differ

Ensuring Lock Files Are in Sync

Often, we may commit when the lock file is out-of-sync with package.json. We can prevent this by using Git hooks by checking whether the lock file is up-to-date in a precommit hook. This is a shell script that lives in .git/hooks/pre-commit. If you use npm and package-lock.json, then .git/hooks/pre-commit looks like the following:

if npm install --package-lock-only && git diff --exit-code package-lock.json; then
  echo package-lock.json is up-to-date
  exit 0
else
  echo ERROR package-lock.json is outdated
  exit 1
fi

If you use pnpm and pnpm-lock.yaml, then it looks like the following:

if pnpm install --lockfile-only && git diff --exit-code pnpm-lock.yaml; then
  echo pnpm-lock.yaml is up-to-date
  exit 0
else
  echo ERROR pnpm-lock.yaml is outdated
  exit 1
fi