导出内联定义或文件末尾的es6默认类? [英] Export an es6 default class inline with definition or at end of file?

查看:61
本文介绍了导出内联定义或文件末尾的es6默认类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

导出内联其定义的es6默认类与定义后在文件末尾之间有什么区别?

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?

以下是我在React教程中遇到的两个示例.

Following are two examples I came across in React tutorials.

例如1:内联类

export default class App extends React.Component {
    // class definition omitted
}

例如2:文件结束

class App extends React.Component [
    // class definition omitted
}

export default App; // is this different somehow?

如果没有区别,那么第一个示例似乎更加高效和简洁.

If there is no difference, then it seems the first example is more efficient and concise.

推荐答案

唯一的区别是,当导出除类或命名函数声明以外的内容时,先声明表达式,然后再导出它,便可以引用它同一模块中的其他位置.

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>

这篇关于导出内联定义或文件末尾的es6默认类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆