Babel Is Lying To You

Yes, babel is a legendary tool. You can use whatever esoteric language features of Tomorrow’s JavaScript, and babel will compile it down to work in IE11 or whatever.

babel is one of those tools that is so pervasive, React can’t even work without it. It’s in every React project I’ve ever touched.

There’s one problem, though: babel let’s you write syntactically incorrect JavaScript, and it will work just fine in the browser. The code you write is not the code you run. babel is lying to you.

We often make note that "variables are hoisted in JavaScript", but this doesn’t apply to es6+ let and const variables, only legacy var variables. let and const aren’t hoisted, so we can’t use them before they are declared.

In frontendland, however, the sweet, warm pillow of babel has lulled us into oblivion, causing us to often forget that let and const are not hoisted, because they act as hoisted post-transpilation. This is leading to lots of syntactically incorrect JavaScript appearing in the wild.

Depending on your compile target, babel will most likely transpile const and let to use var 💀

See this article about styled components, in which the author mentions that they declare styles at the bottom of the file, and the component at the top.

If we were to do this in a “real” JS runtime, we would get an error. Consider the following example.

// index.js
;(() => {
 console.log({bro});
 const bro = 'eyey';
})();

If we run node ., we will see error:

ReferenceError: Cannot access 'bro' before initialization

So yeah, as a result, all React code is tightly coupled to Babel. Among a plethora of other build tools.

That’s it. That’s my rant. Yep, I’m petty.

Key visual: cool green building nearby my company in Shanghai, where I store my bike

end of storey Last modified: