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

后端 未结 1 1720
甜味超标
甜味超标 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:

    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:

    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:

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