How can I whitelist a single file in a directory in .npmignore?

9.4k views Asked by At

I'm trying to make npm download only a single file in a directory on npm install of the package.

The directory looks like:

+- dist/
   +- 1.0.0/
   +- 1.0.1/
   +- ...lots of other dirs...
   +- file.js

I want npm to ignore everything but file.js so I tried including the following in my .npmignore:

dist/
!dist/file.js

Yet, npm will still download all the directories in dist when I install the package. I thought this was supposed to work like .gitignore but apparently I am missing something here.

2

There are 2 answers

4
krampstudio On BEST ANSWER

Yes, it is working using glob patterns : https://docs.npmjs.com/misc/developers#keeping-files-out-of-your-package

But I would have a different approach :

dist/*
dist/.*
!dist/file.js

in order to no ignore the whole folder but it's content (the 2nd line may not be required).

4
Ciro Santilli OurBigBook.com On

Recommendation: whitelist instead of blacklist

Answering the use case, I would instead recommend explicitly white listing what you want to publish with the files entry in package.json, rather than blacklisting with .npmignore, as that makes it is much more likely that you will not accidentally publish the wrong files. See also: https://medium.com/@jdxcode/for-the-love-of-god-dont-use-npmignore-f93c08909d8d

Here's a concrete example package which looks a bit like:

{
  "files": [
    "gitignore",
    "cirodown",
    "cirodown.js",
    "cirodown.embed.min.css",
    "cirodown.local.min.css",
    "cirodown.min.css",
    "index.js",
    "main.liquid.html",
    "main.scss",
    "nodejs.js"
  ],
}