Home

npmignore vs gitignore ― Which one to use?

If you are publishing a package on npm, you should read this post. In this post I had made a clear differece between npmignore and gitignore. And at the end I will tell you the best way to ignore files in your npm package.

What is gitignore

.gitignore is a file used to ignore files while pushing your code from local repo to github or any other source control.

What is npmignore

.npmignore is a file used to ignore files while publishing your node package to npm registry. By using a .npmignore file in your node package root you can keep stuff out of your package.

Which one to use?

npm will use .gitignore file to ignore files if there is no .npmignore file in your package. So you can use it in most of the cases without having a .npmignore file in your package. In addition to this feature, npm ignores some paths by default, for e.g., .DS_Store,.git,etc.,.

Testing whether your .npmignore or files config works:

If you want to double check that your package will include only the files you intend it to when published, you can run the following command:

  npm pack && tar -xvzf *.tgz && rm -rf package *.tgz

Special use-cases for .npmignore

At the first glance you might think that .gitignore can be used for any project that you might encounter with. But there are certain situations we need to ignore some more files in addition to what .gitignore does.

Some files are not needed to be added in any npm package, so publishing these to npm is pointless:

These should generally be ignored by npm, but not by git.

And if you publish your package with github actions, then your workflow files should also be ignored by npm to make your package lean.

So in all the above cases you need a .npmignore file in your package.

You need to be more careful while you use .npmignore file. Because if your package consists both .gitignore and .npmignore, npm uses only .npmignore. So you need to be more conscious that you copy everything you have in .gitignore to *npmignore and then add more paths to it.

And moreover you need to keep updating it whenever you change .gitignore.

Best way to avoid this overhead

After some research I found a better way to ignore files for npm. This solution make use of files property in the package.json file. This way you can allow(whitelist) specific files explicitly to be a part of your package. All other files will be ignored by npm when you publish it. I recommend this whitelisting method over .npmignore.

{
  "name": "PACKAGE_NAME",
  "main": "./lib/index.js",
  "files": [
    "/lib"
  ]
}

You dont have to worry about some files which are included in your package by default while publishing. These paths are not ignored even you place them in .npmignore:



Last Updated on

Next Post: Rules vs Guidelines →

Comments