Export an es6 default class inline with definition or at end of file?

后端 未结 1 1733
甜味超标
甜味超标 2020-12-19 03:07

What is the difference if any between exporting an es6 default class inline with its definition versus at the end of the file after its definition?

Following are two

相关标签:
1条回答
  • 2020-12-19 03:31

    The only significant difference is that, when exporting something other than a class or a named function declaration, declaring the expression and then exporting it afterwards allows you to reference it elsewhere in the same module.

    Class names and (non-arrow, named) function declarations have their name put into the module's scope as a variable:

    <script type="module">
    export default class App {
        // class definition omitted
    }
    console.log(typeof App);
    </script>

    <script type="module">
    export default function fn() {
        
    }
    console.log(typeof fn);
    </script>

    But this isn't possible for other sorts of expressions, like plain objects or arrow function expressions, which don't intrinsically have a name associated with them:

    <script type="module">
    export default {
      prop: 'val'
      // There's no way to reference the exported object in here
    }
    // or out here
    </script>

    <script type="module">
    export default () => 'foo';
    // There's no way to reference the exported function elsewhere in this module
    </script>

    Well, there's one way to get back a reference to it, which is by importing the current module that you're in:

    // foo.js
    import foo from './foo';
    export default () => {
      console.log('foo is', typeof foo);
    };
    

    But that looks really ugly and confusing.

    So if you're default-exporting something which isn't a class nor a function declaration, you can't easily reference what you're exporting unless you put it into a standalone variable before exporting it.

    Keep in mind that this is not the case for named exports, which can easily be referenced by the name of their export:

    <script type="module">
    export const obj = {
      prop: 'val'
    };
    console.log(typeof obj);
    
    export const fn = () => 'foo';
    console.log(typeof fn);
    </script>

    0 讨论(0)
提交回复
热议问题