94

I have a file that is generated by npm install command (using preinstall task). I don't want to add it in the git repository, nor in the NPM project.

Supposing the file name is foo.json, I added it in .gitignore file as foo.json.

Is this enough to avoid uploading it on NPM registry?

I know I can add .npmignore file that will surely ignore the file, but I won't add it if .gitignore already does this.

2 Answers 2

157

If a project has both .npmignore and .gitignore, npm will only use the .npmignore file.

From the documentation:

Use a .npmignore file to keep stuff out of your package. If there's no .npmignore file, but there is a .gitignore file, then npm will ignore the stuff matched by the .gitignore file. If you want to include something that is excluded by your .gitignore file, you can create an empty .npmignore file to override it.

In simpler terms, npm prefers the .npmignore file, but it will fall back to the .gitignore file.

In many cases, both Git and npm can ignore the same files, so it makes sense to just use a .gitignore file.

If you need npm and Git to ignore different files, then you need to maintain separate .gitignore and .npmignore files.

More information on what to put in .npmignore files: Should I .npmignore my tests?

4
  • 1
    It have a different situation, but quite similar, I have a .gitignore that excludes a dir bin/ where my transcompiled ES6 app goes, so I can push lib/, the ES6 written app. But, as you may figure out, the problem is that the published package in npm must have the bin/ Sep 15, 2016 at 11:14
  • 3
    Sounds like you need an .npmignore file containing the same contents as .gitignore but with the bin/ line removed.
    – cmbuckley
    Sep 15, 2016 at 12:43
  • I want the complete opposite. I want npm to add a folder, despite it being present in .gitignore May 28, 2017 at 16:13
  • @LajosMeszaros the second sentence covers that: “If you want to include something that is excluded by your .gitignore file, you can create an empty .npmignore file to override it.” In your case you will need to copy .gitignore to .npmignore, and remove the folder from .npmignore only.
    – cmbuckley
    May 30, 2017 at 9:11
31

For anyone reading this trying to ignore a file/dir from git but wish to include it in npm publish and have tried using an empty .npmignore file with no luck. This works.

In your .gitignore file, add the file/dir you wish to exclude **/build for example and in your .npmignore file make sure you specify the same file/dir but with the ! prefix so for the build example you would include !**/build

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.