为什么 babel 用 (0, ...)() 包裹 _sourceMapSupport.install()?

Why does babel wrap _sourceMapSupport.install() with (0, ...)()?

我注意到 babel 转译了

import { install } from 'source-map-support';
install();

进入

var _sourceMapSupport = require('source-map-support');
(0, _sourceMapSupport.install)();

为什么 babel0 中使用逗号运算符作为调用 install 函数的第一个表达式?

逗号在What does a comma do in JavaScript expressions?中有解释。基本上,它计算所有表达式,returns 最后一个返回的值。

可能,使用它的原因是能够像调用方法一样调用方法。

考虑这个函数:

function f() { return this; }

让我们把它变成一个方法:

var o = {f: f}

那么,尽管f === o.f,结果会因你如何称呼而有所不同:

o.f(); // o
f();   // global object (in non-strict mode)
f();   // undefined (in strict mode)

所以 babel 使用逗号方法来获取对函数的引用,而不将其与对象相关联。这样就可以像调用全局函数一样调用该方法,而不是一个。

(0, o.f)(); // global object (in non-strict mode)
(0, o.f)(); // undefined (in strict mode)