Comments are good.

Comments in dense, labrynthine files like package.json are especially good.

But comments in JSON are… if not bad, then hard.

When I was adding Jest as a front-end test suite for work, I wanted a way to explain the weird regex we use for finding test files efficiently. Unfortunately, JSON (and NPM’s parsing of package.json) is persnickety, and doing something like this fails:

{
  "name": "packageName",
  "version": "0.0.0",
  "scripts": {},
  "jest": {
      // The default testRegex has a | in the middle there -- it grabs everything
      // in __test__ and checks all folders recursively for .spec. or .test. This
      // combo of the two works better from an org standpoint and is noticeably
      // faster.
    "testRegex": "(/__tests__/.*(\\.|/)(test|spec))\\.jsx?$"
  },
  "dependencies": {},
  "devDependencies": {}
}

This is invalid JSON, and thus NPM is totally correct in rejecting it.

But how do we add comments, then?

I found the answer in a discussion on the node.js mailing list

As long as I have a say in the matter, package.json file will always be json. If anything, future versions of npm and node will remove features rather than add them. (I’m looking at you, scripts.install ;)

That being said, I completely understand the desire to put additional data into your JSON configuration files. That’s why the “//” key will never be used by npm for any purpose, and is reserved for comments.

If you want to use a multiple line comment, you can use either an array, or multiple “//” keys.

{ “//”: “this is the first line of a comment”, “//”: “this is the second line of the comment” }

{ “//”: [ “first line”, “second line” ] }

Awesome! I was able to tailor this to my needs like so:

{
  "name": "packageName",
  "version": "0.0.0",
  "scripts": {},
  "jest": {
    "//": [
      "The default testRegex has a | in the middle there -- it grabs everything",
      "in __test__ and checks all folders recursively for .spec. or .test. This",
      " combo of the two works better from an org standpoint and is noticeably",
      "faster."
    ],
    "testRegex": "(/__tests__/.*(\\.|/)(test|spec))\\.jsx?$"
  },
  "dependencies": {},
  "devDependencies": {}
}

It’s a little clumsy, but works like a charm.

Liked this post? Follow me!
TwitterRSSEmail