.gitignore to ignore folder in the root directory

You would often ignore files and folders in .git but did you know that these files and folders would get ignored at any folder level if the file or the folder name matches your defined pattern?

For example, if you wanted to ignore the node_modules folder in the .gitignore file, simply defining node_modules would ignore the folder at any level in your code base.

Consider you’ve a project where you are running an express server, where you’ll have node_modules folder at the root. Further, you have a React project nested inside this project which will have a node_modules folder of it’s own. Thus, only using node_modules in the .gitignore file will lead to the modules getting ignored in the base project as well as the react project.

To ensure that you do not end up ignoring the node_modules in both the folders, you could use the below snippet.

// .gitignore file

node_modules // this will end up ignoring all the node_modules folder in the project
/node_modules

Notice a forward slash before the node_modules folder. Using that will only ignore the node_modules folder at a root level.