【发布时间】:2017-06-13 19:42:48
【问题描述】:
在我捆绑了 Webpack 的 JS 应用程序的矿井深处,我找到了这段代码:
var headers = Object.keys(headersObj).map(function (name) {
return [headersObj[name].name, headersObj[name].value]
})
(window).fetch(self._opts.url, // and so on...
这似乎来自 Slack API 节点库(在某种程度上)要求的 stream-http。
这段代码在运行时会抛出这个错误:
VM481:672 Uncaught TypeError: Object.keys(...).map(...) is not a function
at module.exports.ClientRequest._onFinish (eval at App (container.js:94), <anonymous>:672:4)
at module.exports.eval (eval at App (container.js:94), <anonymous>:614:9)
at module.exports.EventEmitter.emit (eval at App (container.js:94), <anonymous>:3615:18)
at finishMaybe (eval at App (container.js:94), <anonymous>:4371:15)
at afterWrite (eval at App (container.js:94), <anonymous>:4253:4)
at afterTick (eval at App (container.js:94), <anonymous>:4719:11)
at Item.run (eval at App (container.js:94), <anonymous>:3037:15)
at drainQueue (eval at App (container.js:94), <anonymous>:3007:43)
如果在未定义的变量上运行Object.keys,则会发生相同的错误。但是,headersObj 已定义,并且是一个对象。
当我将代码更改为:
var headers = Object.keys(headersObj).map(function (name) {
return [headersObj[name].name, headersObj[name].value]
}); // <- please note yon semicolon
(window).fetch(self._opts.url, // and so on...
它工作正常。问题是,这不是我的代码。我无法轻松地在捆绑脚本的上游添加分号。
- 为什么这个分号看起来很有必要?
- 如何在不更改源代码的情况下解决此问题?
编辑
看起来问题(在 cmets 中指出)是原始代码被解释为:
var headers = Object.keys(headersObj).map(function (name) {
return [headersObj[name].name, headersObj[name].value]
})(window).fetch(self._opts.url, // and so on...
这更清楚地是对传入window的结果(它是一个列表,而不是一个函数)的调用。
window 的实例正在由 Webpack 插件生成:
plugins: [
new webpack.DefinePlugin({
global: 'window'
})
],
这似乎隐含地将window 包装在括号中。有没有办法改变这种行为?
【问题讨论】:
-
这似乎是 js 缩小的问题,其中这些行在不使用分号的情况下将
})(window连接在一起,因此使用分号,即使在 js 缩小之后,这两行也将});(window分开。
标签: javascript syntax webpack