Search code examples
typescriptwebpackecmascript-6babeljsbabel-loader

How to make babel output classes as named functions?


Right now it translates class X { ... } to var X = function X(...) { ... }, how do I make it output it as function X (...) { ... }?


Solution

  • The difference between function declarations and ES6 classes is that function declarations are hoisted:

    console.log(Foo); // Foo
    function Foo() {}
    

    And classes are in temporal dead zone:

    console.log(Foo); // ReferenceError
    class Foo {}
    

    It would be incorrect to transpile a class to function declaration, and the correct function representation of ES6 class is:

    const Foo = function Foo() {};
    

    Since there is no const in ES5, Babel transpiles it to var, also tries to mimic temporal dead zone where possible when respective transform is enabled.