How to add a directory but ignore included files in git
- Published at
- Updated at
- Reading time
This post is a quick reference for my future self. I implemented the eleventy cache assets plugin to speed up my local development last weekend. This site is based on API data from several sources, and unfortunately, local development became terribly slow. It was time for some optimization. The problem was that the local build process fetched all the API data on every file change and local rebuild.
The eleventy cache plugin helps here. It caches data across builds and writes the API data into files in a
directory. When the site rebuilds, the cached data is reused, and no APIs will be called during the build process.
To make the plugin work in a remote environment such as Netlify, it needs the
directory to be available. This behavior led to the problem that I had to check in the
directory but needed to ignore all the included files.
I ran into this exact problem many times, and it always takes me several attempts to get it right. Here's the solution that worked for me.
First, add the directory to your local project and place a
file in it.
.cache |_ .gitignore
Then, paste the following configuration into the
file in the directory you want to check in.
# File: .cache/.gitignore # Ignore everything in this directory * # Except for this file !.gitignore
And voilà! Commit the
folder-you-want-to-check-in/, and that's it! The directory is now available in git and files in this directory will be ignored.
It's to point out that
files work in sub-directories and allow you to configure git on a sub-directory level. And that's pretty handy!