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

标签 javascript webpack

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/

相关文章:

javascript - Express 中的路由参数为空

javascript - 在Electron渲染器进程中持久化nedb到磁盘(Webpack/Electron/nedb配置问题)

ssl - 配置文件中的 webpack4 webpack-dev-server ssl

twitter-bootstrap - 如何在 Rails 5.1 中覆盖 Node Bootstrap 样式?

javascript - 将 jquery-mobile 与 Webpack 结合使用

javascript - 基于输入术语的文本突出显示行为异常

javascript - 在 Img 上悬停在另一个 div 中显示文本

javascript - 如何在 Javascript 命名空间脚本中创建函数数组

javascript - Firebase CORS、白名单 IP 范围

javascript - Vue CLI 3 vue.config.js 与插件的 webpack.config.js