Compiling Es6 Arrow Functions To Es5 Using Babel.js
Solution 1:
tl;dr: Babel assumes every file is a module. Modules are strict by default and their this
value is undefined
.
This is covered in the Babel FAQ:
Babel assumes that all input code is an ES2015 module. ES2015 modules are implicitly strict mode so this means that top-level
this
is notwindow
in the browser nor is itexports
in node.If you don't want this behaviour then you have the option of disabling the strict transformer:
$ babel --blacklist strict script.jsrequire("babel").transform("code", { blacklist: ["strict"] });
PLEASE NOTE: If you do this you're willingly deviating from the spec and this may cause future interop issues.
See the strict transformer docs for more info.
Solution 2:
You are correct in principle, as described on MDN. However, Babel always places a 'use strict'
at the root scope. In effect you compile the following:
'use strict';
varf = () => { 'use strict'; returnthis};
In that case strict rules do apply. See the compiled example here. Babel even optimizes away the top-level this
as it is guaranteed to be undefined
.
Post a Comment for "Compiling Es6 Arrow Functions To Es5 Using Babel.js"