Reputation: 23
Upon reading webpack config docs, something came across that I cannot fully understand.
As I know, we can define global constant with the DefinePlugin
like below, at the compilation(build) time.
new webpack.DefinePlugin({
PRODUCTION: JSON.stringify(true),
VERSION: JSON.stringify('5fa3b9'),
BROWSER_SUPPORTS_HTML5: true,
TWO: '1+1'
});
As we can see usage above, there no needs to be any quotes for the keys.
But we have to use quotes for enabling or disabling feature flags like below.
new webpack.DefinePlugin({
'NICE_FEATURE': JSON.stringify(true),
'EXPERIMENTAL_FEATURE': JSON.stringify(false)
});
I might guess if that feature flags are similar to reserved keywords.
But I cannot find the list of feature flags provided by webpack in default.
So what exactly is that feature flags? Why do we need to use those quotes around the keys when enabling/disabling feature flags?
Thanks in advance.
Upvotes: 2
Views: 415
Reputation: 35473
DefinePlugin
is a plugin which replaces variables inside your bundle with the configured values.
It accepts a regular POJO (Plain Old JavaScript Object), this means that all the rules that applies on POJO's should apply on the config object.
Actually,
new webpack.DefinePlugin({
NICE_FEATURE: JSON.stringify(true),
EXPERIMENTAL_FEATURE: JSON.stringify(false)
});
is a valid object config as well.
If your variable name will contain any invalid character for object key, you should wrap it with quotes.
For example, common usage of DefinePluin
is to replace process.env.NODE_ENV
to it's value. Since the .
character is not a valid char for object key in JS it should be warped with quotes.
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(true),
// --------------------^
});
The "confusing" part of DefinePlugin
is that it requires a valid string as a value, since it replaces variables in side the bundle.
Consider that your value has quotes in it (lets say, company name with "
), therefore, a valid string for it should be "company name with \""
, in order to achieve this value, usually ppl are using JSON.stringify
which escapes any json related chars, one of them is the "
char.
Hope it helps :]
Upvotes: 1