我有一个简单的包裹。json文件,我想添加一个评论。有办法做到这一点吗,或者有什么hack可以做到这一点吗?

{
  "name": "My Project",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
    "express": "3.x",
    "mongoose": "3.x"
  },
  "devDependencies" :  {
    "should": "*"
    /* "mocha": "*" not needed as should be globally installed */
  }
}

上面的示例注释在npm崩溃时不起作用。我还尝试了// style注释。


当前回答

除了全局的//注释(或注释数组)之外,你还可以使用semver管道分隔符对特定依赖项进行注释。

"@types/node": "^16.11.7 || keep-same-major-version-as-node"

其他回答

因为大多数开发人员都熟悉基于标记/注释的文档,所以我开始使用的约定是类似的。来尝尝:

{
  "@comment dependencies": [
    "These are the comments for the `dependencies` section.",
    "The name of the section being commented is included in the key after the `@comment` 'annotation'/'tag' to ensure the keys are unique.",
    "That is, using just \"@comment\" would not be sufficient to keep keys unique if you need to add another comment at the same level.",
    "Because JSON doesn't allow a multi-line string or understand a line continuation operator/character, just use an array for each line of the comment.",
    "Since this is embedded in JSON, the keys should be unique.",
    "Otherwise JSON validators, such as ones built into IDEs, will complain.",
    "Or some tools, such as running `npm install something --save`, will rewrite the `package.json` file but with duplicate keys removed.",
    "",
    "@package react - Using an `@package` 'annotation` could be how you add comments specific to particular packages."
  ],
  "dependencies": {
    ...
  },
  "@comment scripts": {
    "build": "This comment is about the build script.",
    "start": [
      "This comment is about the `start` script.",
      "It is wrapped in an array to allow line formatting.",
      "When using npm, as opposed to yarn, to run the script, be sure to add ` -- ` before adding the options.",
      "",
      "@option {number} --port - The port the server should listen on."
    ],
    "test": "This comment is about the test script.",
  },
  "scripts": {
    "build": "...",
    "start": "...",
    "test": "..."
  }
}

注意:对于dependencies、devDependencies等部分,注释注释不能直接添加到配置对象中各个包依赖项的上面,因为npm期望键是npm包的名称。这就是@comment依赖的原因。

我喜欢在JSON中添加注释的注释/标记样式,因为@符号与普通声明不同。

年长的建议

以下是我之前的建议。它内联注释的脚本,但我已经意识到,这些注释显示为“命令”在一些工具(在VS Code > Explorer > NPM脚本部分)。最新的建议没有受到这个问题的影响,但是脚本注释不再位于同一位置。

{
  "@comment dependencies": [
    ...
  ],
  "dependencies": {
    ...
  },
  "scripts": {
    "@comment build": "This comment is about the build script.",
    "build": "...",

    "@comment start": [
      "This comment is about the `start` script.",
      "It is wrapped in an array to allow line formatting.",
      "When using npm, as opposed to yarn, to run the script, be sure to add ` -- ` before adding the options.",
      "",
      "@option {number} --port - The port the server should listen on."
    ],
    "start": "...",

    "@comment test": "This comment is about the test script.",
    "test": "..."
  }
}

注意:在某些情况下,例如在“scripts”对象中,一些编辑器/ ide可能会抱怨数组。在脚本上下文中,VS Code期望值为字符串——而不是数组。

最近在Node.js邮件列表中讨论了这个问题。

根据创建npm的Isaac Schlueter的说法:

... "//"键永远不会被NPM用于任何目的,它是为注释保留的…如果想使用多行注释,可以使用数组或多个“//”键。

当使用你常用的工具(npm, yarn等)时,多个“//”键将被移除。这生存:

{ "//": [
  "first line",
  "second line" ] }

这将不复存在:

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

必须注意,"//"只能在包的根目录下使用。json对象。例如 { “/ /”:“评论!” “依赖”:{…} } 是有效的但是 { “依赖”:{ “/ /”:“评论?” } } 是无效的。 ——@david_p评论

另一个黑客

我创建了一个脚本来读取文件包。Json作为句柄模板的上下文。

代码如下,以防有人发现这种方法有用:

const templateData = require('../package.json');
const Handlebars = require('handlebars');
const fs = require('fs-extra');
const outputPath = __dirname + '/../package-json-comments.md';
const srcTemplatePath = __dirname + '/package-json-comments/package-json-comments.hbs';

Handlebars.registerHelper('objlist', function() {
  // The first argument is an object, and the list is a set of keys for that obj
  const obj = arguments[0];
  const list = Array.prototype.slice.call(arguments, 1).slice(0,-1);

  const mdList = list.map(function(k) {
    return '* ' + k + ': ' + obj[k];
  });

  return new Handlebars.SafeString(mdList.join("\n"));
});

fs.readFile(srcTemplatePath, 'utf8', function(err, srcTemplate){
  if (err) throw err;
  const template = Handlebars.compile(srcTemplate);
  const content = template(templateData);

  fs.writeFile(outputPath, content, function(err) {
    if (err) throw err;
  });
});

句柄模板文件package-json-comments.hbs

### Dependency Comments
For package: {{ name }}: {{version}}

#### Current Core Packages
should be safe to update
{{{objlist dependencies
           "@material-ui/core"
           "@material-ui/icons"
           "@material-ui/styles"
}}}

#### Lagging Core Packages
breaks current code if updated
{{{objlist dependencies
           "amazon-cognito-identity-js"
}}}

#### Major version change
Not tested yet
{{{objlist dependencies
           "react-dev-utils"
           "react-redux"
           "react-router"
           "redux-localstorage-simple"

}}}

总结一下这些答案:

添加一个名为//的顶级字段,其中包含一个注释字符串。这是可行的,但它很糟糕,因为你不能把评论放在他们正在评论的东西附近。 添加多个以//开头的顶级字段,例如包含注释字符串的//dependencies。这样更好,但仍然只允许您做顶级注释。不能注释单个依赖项。 在脚本中添加echo命令。这是可行的,但它很糟糕,因为您只能在脚本中使用它。

这些解决方案的可读性也都不是很好。它们增加了大量的视觉干扰,ide不会用语法将它们作为注释突出显示。

我认为唯一合理的解决方案是生成包。Json从另一个文件。最简单的方法是将JSON写成JavaScript,然后使用Node.js将其写入package.json。将该文件保存为package.json。chmod +x它,然后你可以运行它来生成你的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));

它使用//键来警告人们不要编辑它。\x40生成是故意的。它变成了@generated in package。Json,这意味着一些代码审查系统将在默认情况下崩溃该文件。

这是构建系统中的一个额外步骤,但它胜过这里的所有其他hack。

正如这个答案所解释的,//键是保留的,所以它可以常规地用于注释。//注释的问题是它不实用,因为它不能被多次使用。在包上删除重复的密钥。Json自动更新:

"//": "this comment about dependencies stays",
"dependencies": {}
"//": "this comment disappears",
"devDependencies": {}

另一个问题是// comment不能在依赖项和devDependencies中使用,因为它被视为常规依赖项:

"dependencies": {
  "//": "comment"
}

npm犯错!代码EINVALIDPACKAGENAME npm犯错!无效的包名“//”:名称只能包含url友好 字符

在NPM中工作的一个变通方法,而不是Yarn,是使用一个非字符串值:

"dependencies": {
  "foo": ["unused package"],
}

一个在NPM和Yarn中工作的变通方法是添加一个注释作为语义版本控制的一部分:

"dependencies": {
  "bar": "^2",
  "foo": "^2 || should be removed in 1.x release"
}

注意,如果OR之前的第一部分不匹配,则可以解析来自注释的版本,例如1.x。

需要注释但没有安装的包应该移动到另一个键,例如dependencies //:

"dependencies //": {
  "baz": "unused package",
}