In Pete Hunt's Webpack How To this code is used:
// definePlugin takes raw strings and inserts them, so you can put strings of JS if you want.
var definePlugin = new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(process.env.BUILD_DEV || 'true')),
__PRERELEASE__: JSON.stringify(JSON.parse(process.env.BUILD_PRERELEASE || 'false'))
});
What is JSON.stringify(JSON.parse(..)) needed here?
JSON stringifying/parsing is useful to clone an object to avoid mutations, but process.env.BUILD_DEV is (and can only be?) a string. So, why use it?
1 Answer 1
This is weird code. First off, the cloning mechanism is:
JSON.parse(JSON.stringify(obj))
But, your code is this:
JSON.stringify(JSON.parse(str))
So, it appears to be attempting to clone a JSON string the hard way. That's bizarre because strings are immutable in Javascript so there's no danger in having multiple references to the same string. The underlying string cannot be changed.
I'd say that this extra code seems redundant and unnecessary unless it's somehow just forcing the value of process.env.BUILD_DEV to be something that JSON.parse() will accept without an exception which seems like a very odd way to test the value. If that was the purpose, the code would be a lot clearer to just check for the expected legal values explicitly rather than some sort of undocumented side effect test like this. Plus we don't see any exception handlers to handle bad data here so it seems less likely that would be the reason for it.
I guess one other reason would be to normalize a string to a canonical format since calling JSON.stringify() on the results of parsing it will guarantee a uniform string no matter what escape characters might have been in the original string. It still seems a bizarre practice without any comments about why it's being done.
var newObj = JSON.parse(JSON.stringify(object))but not the other way around - perhaps it is a hack to make sure the string is valid even when it contains newlines or quotesJSON.stringify()