Recursively ignore all files inside a specific directory except .json files


I have a file structure similar to the one below:


What I want to do is ignore all the files inside the node_modules folder except the json files so that I end up with the following file structure in my repo:


I tried to find a simple way to do that but I’m not quite there yet.

Here’s what I came up with in my .gitignore:

# ignore everything inside node_modules

# But descend into directories

What’s the most elegant way to achieve the desired result?

P.S. I have no idea what I’m doing.


Ok so I finally found a solution. Here’s what did the trick:

# Ignore all the files inside the node_modules folder

# Allow only json files inside the node_modules folder

The issue was that by doing node_modules/*, it would not just ignore files but also folders.

And as the git doc says:

It is not possible to re-include a file if a parent directory of that
file is excluded.

So instead I did node_modules/**/*.* which only exclude files and not folders.

That way, !node_modules/**/*.json is actually able to allow json files.

Answered By – Etienne Martin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published