Why does Webpack’s DefinePlugin require us to wrap everything in JSON.stringify?

The answer is below the example:

  • If the value is a string it will be used as a code fragment.
  • If the value isn’t a string, it will be stringified (including functions).

I.e. the value of a string is inserted into the source code verbatim.

Passing JSON.stringify(true) or passing true directly is the same, since non-string values are converted to strings.

However, there is a big difference between JSON.stringify('5fa3b9') and "5fa3b9":

Assuming your code was

if (version === VERSION)

then VERSION: JSON.stringify('5fa3b9') would result in

if (version === "5fa3b9")

but VERSION: "5fa3b9" would result in

if (version === 5fa3b9)

which is invalid code.

Note that because the plugin does a direct text replacement, the value given to it must include actual quotes inside of the string itself. Typically, this is done either with either alternate quotes, such as ‘”production”‘, or by using JSON.stringify(‘production’).

Leave a Comment