I\'ve got a simple package.json file and I want to add a comment. Is there a way to do this, or are there any hacks to make this work?
NPS (Node Package Scripts) solved this problem for me. It lets you put your NPM scripts into a separate JavaScript file, where you can add comments galore and any other JavaScript logic you need to. https://www.npmjs.com/package/nps
Sample of the package-scripts.js
from one of my projects
module.exports = {
scripts: {
// makes sure e2e webdrivers are up to date
postinstall: 'nps webdriver-update',
// run the webpack dev server and open it in browser on port 7000
server: 'webpack-dev-server --inline --progress --port 7000 --open',
// start webpack dev server with full reload on each change
default: 'nps server',
// start webpack dev server with hot module replacement
hmr: 'nps server -- --hot',
// generates icon font via a gulp task
iconFont: 'gulp default --gulpfile src/deps/build-scripts/gulp-icon-font.js',
// No longer used
// copyFonts: 'copyfiles -f src/app/glb/font/webfonts/**/* dist/1-0-0/font'
}
}
I just did a local install npm install nps -save-dev
and put this in my package.json
scripts.
"scripts": {
"start": "nps",
"test": "nps test"
}
To summarise all of these answers:
Add a single top-level field called //
that contains a comment string. This works, but it sucks because you can't put comments near the thing they are commenting on.
Add multiple top-level fields starting with //
, e.g. //dependencies
that contains a comment string. This is better, but it still only allows you to make top-level comments. You can't comment individual dependencies.
Add echo
commands to your scripts
. This works, but it sucks because you can only use it in scripts
.
These solutions are also all not very readable. They add a ton of visual noise and IDEs will not syntax highlight them as comments.
I think the only reasonable solution is to generate the package.json
from another file. The simplest way is to write your JSON as JavaScript and use Node.js to write it to package.json
. Save this file as package.json.mjs
, chmod +x
it, and then you can just run it to generate your package.json
.
#!/usr/bin/env node
import { writeFileSync } from "fs";
const config = {
// TODO: Think of better name.
name: "foo",
dependencies: {
// Bar 2.0 does not work due to bug 12345.
bar: "^1.2.0",
},
// Look at these beautify comments. Perfectly syntax highlighted, you
// can put them anywhere and there no risk of some tool removing them.
};
writeFileSync("package.json", JSON.stringify({
"//": "This file is \x40generated from package.json.mjs; do not edit.",
...config
}, null, 2));
It uses the //
key to warn people from editing it. \x40generated
is deliberate. It turns into @generated
in package.json
and means some code review systems will collapse that file by default.
It's an extra step in your build system, but it beats all of the other hacks here.