为什么Webpack的DefinePlugin要求我们将所有东西都包装在JSON.stringify中? [英] Why does Webpack's DefinePlugin require us to wrap everything in JSON.stringify?

查看:244
本文介绍了为什么Webpack的DefinePlugin要求我们将所有东西都包装在JSON.stringify中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

new webpack.DefinePlugin({
    PRODUCTION: JSON.stringify(true),
    VERSION: JSON.stringify("5fa3b9"),
    BROWSER_SUPPORTS_HTML5: true,
    TWO: "1+1",
    "typeof window": JSON.stringify("object")
})

https://github.com/webpack/docs/wiki/list-of-plugins#defineplugin

这似乎很不寻常,不必要和开发 - 易出错的。

This seems very unusual, unnecessary and "dev-error-prone".

是否存在类型检查问题?

Is it type-checking concerns?

推荐答案

答案在下面的例子中:



  • 如果值是一个字符串,它将被用作代码片段。

  • 如果该值不是字符串,则将进行字符串化(包括函数)。

即字符串的值插入源代码 verbatim

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

传递 JSON.stringify(true)或直接传递 true 是相同的,因为非字符串值会转换为字符串。

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

但是, JSON.stringify('5fa3b9')5fa3b9之间存在很大差异:

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

假设你的代码是

if (version === VERSION)

然后 VERSION:JSON.stringify('5fa3b9')会导致

if (version === "5fa3b9")

但是 VERSION:5fa3b9会导致

if (version === 5fa3b9)

这是无效的代码。


请注意,因为插件执行直接文本替换,所以赋予它的值必须包含其中的实际引号字符串本身。通常,这可以使用备用引号(例如production)或使用JSON.stringify('production')来完成。

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').

这篇关于为什么Webpack的DefinePlugin要求我们将所有东西都包装在JSON.stringify中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆