Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've noticed that babel transpiled

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

into

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

Why did babel use the comma operator with 0 as first expression in the invocation of the install function?

like image 655
borisdiakur Avatar asked Sep 27 '22 10:09

borisdiakur


1 Answers

The comma is explained in What does a comma do in JavaScript expressions?. basically, it evaluates all the expressions, and returns the value returned by the last one.

Probably, the reason for using that is to be able to call the method as if it weren't a method.

Consider this function:

function f() { return this; }

And let's make it a method:

var o = {f: f}

Then, although f === o.f, the result will vary depending on how you call it:

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

So babel uses the comma approach to get a reference to the function, without associating it with the object. This way the method can be called as if it were a global function, without being one.

(0, o.f)(); // global object (in non-strict mode)
(0, o.f)(); // undefined (in strict mode)
like image 55
Oriol Avatar answered Sep 30 '22 15:09

Oriol