Suitable `.gitignore` For Node.js

31,603

Solution 1

Since your structure is quite organized you could use this pattern to accomplish the task.

/node_modules/*/node-modules/ 

The above pattern will ignore node_modules under module folders, my-mod1,my-mod4 and others.

The above line will still allow the node_modules under src directory to be included when you push to github.

Solution 2

node_modules/**/node_modules should work for what you are trying to do.

Tip: GitHub provides standard .gitignore's for various languages like Node.

Solution 3

Thanks for your answers.

I rethought the condition and decided to declared the condition the other way - it works perfectly:

node_modules/*/node_modules

I hope this is able to help anybody in the future.

Share:
31,603
fdj815
Author by

fdj815

Updated on March 08, 2020

Comments

  • fdj815
    fdj815 about 4 years

    Tree structure

    That's how my Node.js project is organized:

    /
    | - node_modules               [+ INCLUDE]
    |   | - my-mod1
    |   |   | - node_modules       [- IGNORE]
    |   |   |   | - external-mod1 
    |   |   |   | - external-mod2 
    |   |   | - src
    |   |   |   | - node_modules   [+ INCLUDE]
    |   |   |   |   | - my-mod2 
    |   |   |   |   | - my-mod3
    |   | - my-mod4
    

    My plan

    When publishing my project to GitHub:

    • I want to include my-mods.
    • I don't want to include the external-mods.

    That means:

    • I want to include the top-level /node_modules folder.
    • I don't want to include node_modules folders which are direct childs of a module folder.
    • But I want to include node_moduels folders which are childs of a src folder.

    What I did

    I added the following lines to /.gitignore:

    #################  
    ## npm
    #################
    
    npm-debug.log
    node_modules/
    !/node_modules/
    !src/node_modules/
    

    My question

    Which .gitignore rules do I need to include the right node_modules folders (as described above)?

    Thanks - if anything's unclear, please comment.

  • fdj815
    fdj815 about 11 years
    Thanks for your answer. - I already knew the github/gitignore repository, but there wasn't anything suitable for my usecase.
  • ben.snape
    ben.snape about 11 years
    I thought you probably did but it's always handy to point out :-) did the .gitignore line work for you?
  • fdj815
    fdj815 about 11 years
    No, it's a good idea (thanks), but unfortunately didn't handle the ./node_modules inside the src folders correctly. - I tried to define the condition in another way (see my own answer).