Function Call Rewriting in Babel: Understanding the Comma Operator
Babel, a popular JavaScript compiler, converts ES6 code into compatible versions for older browsers. When encountering a function call from an imported module, Babel often adds a comma operator (0,) to the beginning of the call. This behavior raises questions about its purpose.
Specifically, an input file containing an import function call:
import { a } from 'b'; function x () { a() }
is compiled by Babel into:
'use strict'; var _b = require('b'); function x() { (0, _b.a)(); }
Babel's default behavior is to compile in strict mode, hence the (0,). In loose mode, the function call is output as _b.a() without the comma operator.
Explaining the Comma Operator
The addition of (0,) ensures that the imported function is called with the global object as its this value, or undefined if strict mode is enabled. Without the comma, _b.a() would be called with _b as its this value.
The comma operator evaluates the first expression (0) to undefined and ignores its result. It then evaluates the second expression (_b.a) and assigns it to a temporary variable (tmp). Finally, it calls the temporary variable (tmp()) with the global object as its this value.
In essence, this technique allows the imported function to operate globally without affecting the this value of the calling context.
Conclusion
Babel's use of the comma operator in imported function calls ensures that the function is called correctly regardless of the calling context. This technique is implemented by discarding the first comma expression result and calling a temporary variable with the global object as its this value.
The above is the detailed content of Why Does Babel Add a Comma Operator (0,) to Imported Function Calls?. For more information, please follow other related articles on the PHP Chinese website!