Control What you Publish Inside your Npm Packages

The own your mistakes edition

David Barral
Trabe
2 min readMay 5, 2021

--

Photo by Brett Jordan on Unsplash

In February 2020 I’ve published a story with this same title. In this story, I argued that it was hard to determine what to include and exclude in an npm package using the files field in the package.json and the .npmignore file.

The fact is that, at the time, I thought it was not possible to define exclude patterns in the files field, and offered an Adhoc solution: preprocess an extended syntax using some scripting before packing.

I was wrong. As a kind reader pointed in the comments: You most certainly can.

The optional files field is an array of file patterns that describes the entries to be included when your package is installed as a dependency. File patterns follow a similar syntax to .gitignore, but reversed.

In a .gitignore file you can use negative patterns prepending an exclamation mark. I guess I missed that.

In my original story, I wanted to pack some React components but exclude the colocated tests. To pack/publish that is as easy as having the following package.json:

The original story still has some valid points, like the advantages of using package.js files or how convoluted are the files vs .npmignore rules (as you can read in the npm docs). You can still use the preprocess approach to solve other package.json limitations. However, it does not change the fact that the info I provided was not 100% accurate. You don’t need to do anything fancy or special to control the contents of an npm package

How did I miss that?

Truly, I have no clue 🤷🏻‍♂️.

I don’t fancy fixing problems that do not exist. So it’s quite baffling to find that this support has been there for a long, long time. Since npm version 4, at least.

I surely misread the docs. I didn’t find further info on the web. I didn’t test enough the tools. Therefore, I got to a bad conclusion.

My humble apologies

If you read that story and followed my advice, I’m sorry. This story is my apology. I hope you find useful to know the real solution to the problem. I do.

Writing tech stuff is hard. Sometimes this happens. You share trying to help other people to fix a problem that you struggled with, and, in the end, you end up misleading. When this happens I think the honest thing to do is to own your mistake: admit it, give better information and fix it, apologize and learn.

--

--

David Barral
Trabe

Co-founder @Trabe. Developer drowning in a sea of pointless code.