5

I started a project using npm, added a few dependencies and then initialized the repository usign git init.

I wanted the directory node_modules to be ignored by git, so I added it to the .gitignore file like so.

.gitignore

node_modules/

Of course because node_modules was added before git init, it is still recognized as a directory to track.

So I deleted it, used the following commands (as suggesed for similar problems)

git rm -r --cached .
git add .
git commit -m ".gitignore should now work"

Then reinstalled the npm dependencies by using npm install

After this I expect to have the directory node_modules to be finally ignored. Instead if I type git status I get

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    node_modules/

Why?

Carlo
  • 582
  • 1
  • 4
  • 16
  • Is this exactly the sequence you used? I cannot reproduce this result. – Dan Lowe Jan 13 '18 at 16:17
  • @DanLowe yes, I have double and triple checked, but nothing, it doesn't work.This looks absurd to me. – Carlo Jan 13 '18 at 16:39
  • I too couldn't reproduce this. Tried the following steps: `git init; echo "Myfile" > myfile; mkdir node_modules && echo "module" > node_modules/module.txt; git commit -m "init"; echo "node_modules" > .gitignore; rm -rf node_modules/; git rm -r --cached .; git add .; git commit -m ".gitignore should now work"; mkdir node_modules; echo "module" > node_modules/mod.txt; `. `git status` gives "On branch master nothing to commit, working tree clean" after running these. – Bless Jan 18 '18 at 15:52
  • @bless just tried again doing the same you did, but still have `node_modules/` as untracked after `git status` – Carlo Jan 18 '18 at 16:12
  • `git rm -r --cached .` was the solution for me. After running this command, `node_modules` from `.gitignore` worked well. – Felix Htoo Jun 02 '21 at 16:17

2 Answers2

7

Under this question there are many possible fixes for a .gitignore file not properly working.

In this case the problem is (was) that the .gitignore file's encoding was UNICODE instead of ASCII

Carlo
  • 582
  • 1
  • 4
  • 16
5

Try the following:

  • Remove node_modules from .gitignore and save it

  • Delete node_modules (or move it somewhere outside from the project directory)

  • Commit the changes (there will be a tons of deletion from node_modules) This step will remove the files from source control.

  • Add node_modules to .gitignore again

  • Commit gitignore

  • Re-run npm install or restore the node_modules directory.

Lajos Gallay
  • 1,083
  • 9
  • 16