I need to add comments to my JSON without using another NPM package, so I had the idea to add module.exports =
to the start of my JSON file so that it becomes a CommonJS module (with a normal JS Object) that I can use in the exact same way. Are there any trade-offs I need to know when doing this?
You can certainly do this:
const data = require('myfile.json');
with JSON data in the file:
{"someProp": "someValue"}
Or, you can do this:
const data = require('mfile.js');
with this in the file:
module.exports = {"someProp": "someValue"};
One is a module file. One is a JSON file. It really just depends upon what you want it to be or if there are any other clients of this file that expect it to be one way or the other. There are no specific advantages or disadvantages either way, though the CommonJS module can contain more types of data, comments, etc... because JSON is very restrictive about what could be in there. Both will work just fine for the core data if you follow the appropriate format rules.
If you want to add Javascript comments to the data, then you cannot do that in JSON so you will need to make it a module and there's no specific drawback to doing that.
Note, for require()
to automatically parse the JSON, it has to have a .json
file extension. For it to be parsed as a Javascript CommonJS module, it must not have a .json
file extension.