javascriptes6-modules

Are these export syntax the same


I see a lot of people start a component like:

export default function Example(){XYZ}

Is that the same as writing the function and then exporting at the bottom of the page like so?

function Example(){XYZ};

export default Example

Solution

  • For the most part, there isn't much of a difference here. In both cases, you're creating function declarations and then exporting them. While export default can have an expression following it, export default function Example() {} is handled specially and is treated as a function declaration in this case, just like in your first example. And you can see this as you're still able to call Example - meaning its identifier was added to the current scope (which function expressions do not do).

    While you would almost never do this in React code, there is however a small difference:

    // Example.js
    function Example(){XYZ}
    export default Example;
    setTimeout(() => {Example = 123;}, 100);
    

    This exports your function as is, meaning that you can be safe in knowing that Example in the consuming module will always be the function reference that you exported:

    import Example from "./Example.js";
    console.log(Example); // logs the function: ƒ Example() {}
    setTimeout(() => {
      console.log(Example); // logs the function: ƒ Example() {} (even though the binding has been re-assigned in the source module)
    }, 200);
    

    on the other hand:

    // Example.js
    export default function Example(){XYZ}
    setTimeout(() => {
      Example = 123;
    }, 100);
    
    import Example from "./Example.js";
    console.log(Example); // logs the function: ƒ Example() {}
    setTimeout(() => {
      console.log(Example); // logs the number: 123 (changing the binding in the source impacts this)
    }, 200);
    

    In this case, the live binding to Example is exported, and so changing it in the source impacts in it the consuming module - again, rare to do in React code so almost not something you need to worry about. You can read more about this in depth in this great article by Jake Archibald.