Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Babel's funny import

Since no browser I know implements currently the ES6 modules interface - but transpilers do - I tested babel with this simple example

import { getUsefulContents } from "file.js";
getUsefulContents("http://www.example.com", data => {
  doSomethingUseful(data);
  });

I just wanted to see how does it transpile these lines. To my surprise it produced following output:

"use strict";

var _fileJs = require("file.js");

(0, _fileJs.getUsefulContents)("http://www.example.com", function (data) {
  doSomethingUseful(data);
});

The last line looks mysterious to me - especially the (0, _fileJs.getUsefulContents) part, what is going on there? What is the purpose of that (0, ...) on that line?

like image 620
Tero Tolonen Avatar asked Jun 24 '15 19:06

Tero Tolonen


1 Answers

Calling a function like that forces it to call it in the global context.

function whoAmI() {
  document.querySelector('pre').innerText += this.name + '\n';
}
window.name = 'window';
var mike = {
  name: 'mike',
  whoAmI: whoAmI
};
mike.whoAmI();
(0, mike.whoAmI)();
<pre></pre>

The reason this works is because when it evaluates (0, filesJs) it runs through each of the statements in the parentheses, similar to how you can declare multiple variables using a ,

var a = 1,
    b = 2,
    ...

As the last expression is reference to a function, it uses that when evaluating the function call with the next set of parentheses. Being that the expression was already evaluated, the _filesJs context is lost. It's effectively the same as doing this:

0; // Legal, just pointless
var f = _filesJs.getUsefulContents;
f("http://example.com", ...);
like image 146
Mike Cluck Avatar answered Sep 25 '22 13:09

Mike Cluck