gpt4 book ai didi

javascript - 为什么 Webpack 的 DefinePlugin 要求我们把所有东西都包裹在 JSON.stringify 中?

转载 作者:IT王子 更新时间:2023-10-29 03:23:06 25 4
gpt4 key购买 nike

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

这看起来非常不寻常、不必要并且“容易出现开发错误”。

它是类型检查问题吗?

最佳答案

答案在例子下面:

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

即字符串的值被逐字插入到源代码中。

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

但是,JSON.stringify('5fa3b9')"5fa3b9"之间有很大的区别:

假设你的代码是

if (version === VERSION)

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

if (version === "5fa3b9")

但是 VERSION: "5fa3b9" 会导致

if (version === 5fa3b9)

这是无效代码。

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

关于javascript - 为什么 Webpack 的 DefinePlugin 要求我们把所有东西都包裹在 JSON.stringify 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39564802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com