[英]Requiring a JSON with comments in node.js
If you use typescript you can init a default tsconfig.json, and that json will have javascript // and /* */ comments in it.如果你使用 typescript 你可以初始化一个默认的 tsconfig.json,并且 json 将有 ZDE9B9ED78D7E2E1DCEEFFEE78E 注释 ///*/ I've encountered a situation with ts-jest where I need to require my tsconfig and parse it, but jest is not parsing it because json doesn't allow comments.
我遇到了 ts-jest 的情况,我需要我的 tsconfig 并解析它,但 jest 没有解析它,因为 json 不允许评论。 see this I'm not sure how typescript handles it, but it seems to deviate from the rule.
看到这个我不确定 typescript 是如何处理它的,但它似乎偏离了规则。
// this fails if tsconfig has comments
const tsconfig = require('./tsconfig')
I want to keep the comments because they are really helpful to understand and maintain my tsconfig.json, and I want to require my config to be able to avoid duplicating code and make things more dynamic.我想保留这些评论,因为它们对理解和维护我的 tsconfig.json 非常有帮助,而且我希望我的配置能够避免重复代码并使事情变得更加动态。
Is there a way to require a json file with comments using nodejs?有没有办法使用 nodejs 要求带有注释的 json 文件?
json5 can do the trick. json5可以解决问题。 Install JSON5 and then:
安装 JSON5,然后:
const JSON5 = require('json5');
const tsconfig = JSON5.parse(jsontxt);
Note that removing comments by yourself is possible but has several pitfalls, and that's why it's not recommended.请注意,自己删除评论是可能的,但有几个陷阱,这就是不建议这样做的原因。 You should look for:
你应该寻找:
"
that don't mark string end such as "foo\"bar"
."
不标记字符串结尾,例如"foo\"bar"
。 It's more confusing with "foo\\"
, where the second " does end the string."foo\\"
更令人困惑,第二个 " 确实结束了字符串。//
comment may contain /*
, but that does not start a multi line comment. //
注释可能包含/*
,但这不会开始多行注释。//
in a multi line comment does not start a single-line comment, such that removing comments in /* // */ "hi"
results with "hi"
.//
不会开始单行注释,因此删除/* // */ "hi"
中的注释会导致"hi"
。\
continue a single-line to the next line? \
是否将单行继续到下一行? Does a \*/
end a multi line comment, or does the \
make the *
act differently? \*/
结束多行注释,还是\
使*
行为不同? (Neither are supported in JavaScript). I managed to do it by pre-processing the json to strip the comments.我设法通过预处理 json 来去除评论来做到这一点。 The following code is doing the job for me:
以下代码为我完成了这项工作:
const fs = require('fs')
const stripForwardSlashForwardSlashComment = new RegExp('//(.*)', 'g')
const stripForwardSlashStarComment = new RegExp('[/][*](.*)[*][/]', 'gm')
let jsontxt = fs.readFileSync('./tsconfig.json', 'utf8')
jsontxt = jsontxt.replace(stripForwardSlashForwardSlashComment,'').replace(stripForwardSlashStarComment, '')
const tsconfig = JSON.parse(jsontxt)
Self answer note: Posting to keep this public and get some feedback自我回答说明:发布以保持公开并获得一些反馈
require-json5
is purpose-built for this: require-json5
是为此专门构建的:
const requireJSON5 = require('require-json5');
const tsconfig = requireJSON5('./tsconfig.json');
Or even more simply:或者更简单:
require('require-json5').replace();
var tsconfig = require("./tsconfig");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.