gitignore a given folder in multiple subfolders

Viewed 387

In my web project, there are two node applications, each having a separate node_modules folder.

main_folder has a client folder and server folder, which are two separate node apps.

I have created a .gitignore file inside main folder and I wish to ignore node_modules folders in both node apps. How do I do that?

Thanks in advance.

2 Answers

Add node_modules/ to .gitignore in main directory.

Each line in .gitignore represents a pattern that will make git ignore specific files and directories. It should cover all subdirectories as well.

There are two ways to ignore the node_modules subfolder. You can ignore it in the main folders .gitignore file or from the node apps subfolders .gitignore file.

Example folder structure

main
|-- client
|   |-- foo
|   |   |-- foo.txt
|   | 
|   |-- bar
|   |   |-- bar.txt
|   |
|   |-- node_modules
|   |   |-- modules.txt
|
|-- server
|   |-- foo
|   |   |-- foo.txt
|   | 
|   |-- bar
|   |   |-- bar.txt
|   |
|   |-- node_modules
|   |   |-- modules.txt

Ignore it from the main folder

Add a .gitignore file to the main folder with the following pattern:

/**/node_modules/
main
|-- ...
|-- .gitignore

Ignore it from the app subfolders

The patterns from .gitignore in subfolders override the patterns from parent folders. This means you can also add a .gitignore to each app subfolder with the following pattern:

/node_modules
main
|-- client
|   |-- ...
|   |-- .gitignore
|
|-- server
|   |-- ...
|   |-- .gitignore

From the git documentation

Patterns read from a .gitignore file in the same directory as the path, or in any parent directory, with patterns in the higher level files (up to the toplevel of the work tree) being overridden by those in lower level files down to the directory containing the file. These patterns match relative to the location of the .gitignore file. A project normally includes such .gitignore files in its repository, containing patterns for files generated as part of the project build.

Related