我有一个简单的包裹。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注释。
在浪费了一个小时的复杂和俗套的解决方案后,我找到了注释package.json中庞大的依赖项部分的简单而有效的解决方案。就像这样:
{
"name": "package name",
"version": "1.0",
"description": "package description",
"scripts": {
"start": "npm install && node server.js"
},
"scriptsComments": {
"start": "Runs development build on a local server configured by server.js"
},
"dependencies": {
"ajv": "^5.2.2"
},
"dependenciesComments": {
"ajv": "JSON-Schema Validator for validation of API data"
}
}
当以同样的方式排序时,现在我很容易在Git提交差异中或在编辑器中跟踪这些依赖/注释对,同时使用package.json文件。
不需要使用额外的工具,只需要简单有效的JSON。
我有一个有趣的黑客想法。
创建一个适当的npm包名,作为文件包中的依赖项和devDependencies块的注释分隔符。Json,例如x----x----x
{
"name": "app-name",
"dependencies": {
"x----x----x": "this is the first line of a comment",
"babel-cli": "6.x.x",
"babel-core": "6.x.x",
"x----x----x": "this is the second line of a comment",
"knex": "^0.11.1",
"mocha": "1.20.1",
"x----x----x": "*"
}
}
注意:您必须在最后一个注释分隔行中添加一个有效的版本,如块中的*。
我一直在这样做:
{
...
"scripts": {
"about": "echo 'Say something about this project'",
"about:clean": "echo 'Say something about the clean script'",
"clean": "do something",
"about:build": "echo 'Say something about building it'",
"build": "do something",
"about:watch": "echo 'Say something about how watch works'",
"watch": "do something",
}
...
}
这样,我既可以读取脚本本身的“伪注释”,也可以运行如下代码,在终端中查看某种帮助:
npm run about
npm run about:watch
如果你用的是纱线就更好了。
yarn about:clean
此外,正如@Dakota Jang在评论中指出的那样,你可以使用//之类的键来更清楚地表明这是一条评论。
像这样:
{
...
"scripts": {
"//clean": "echo 'Say something about the clean script'",
"clean": "do something",
"//build": "echo 'Say something about building it'",
"build": "do something",
"//watch": "echo 'Say something about how watch works'",
"watch": "do something",
}
...
}
然后运行:
npm run //build
# or
yarn //build
在终端中会有一个helper输出,在包中会有一个“comment”。Json也是。
您总是可以滥用重复的键会被覆盖的事实。这就是我刚才写的:
"dependencies": {
"grunt": "...",
"grunt-cli": "...",
"api-easy": "# Here is the pull request: https://github.com/...",
"api-easy": "git://..."
"grunt-vows": "...",
"vows": "..."
}
然而,不清楚JSON是否允许复制键(参见
JSON语法是否允许在一个对象中重复键?它似乎与npm一起工作,所以我冒这个险。
推荐的破解方法是使用“//”键(来自nodejs邮件列表)。当我测试它时,它不能处理“依赖”部分。另外,文章中的例子使用了多个“//”键,这意味着npm不会拒绝具有重复键的JSON文件。换句话说,上面的hack应该总是好的。
更新:重复密钥的一个恼人的缺点是npm install——save无声地消除了所有重复密钥。不幸的是,它很容易被忽视,你善意的评论也消失了。
“//”攻击看起来仍然是最安全的。但是,多行注释也会被npm install -save删除。