JavaScript 中“导出”和“导出默认值”之间的区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42478661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:10:46  来源:igfitidea点击:

Difference between 'export' and 'export default' in JavaScript?

javascriptecmascript-6

提问by Jesse

What exactly is the difference between the two? I've seen people use:

两者之间究竟有什么区别?我见过人们使用:

function foo () {
  ...
}

export default foo;

And I've seen:

我见过:

function bar () {
  ...
}

export bar;

Also, why would you use the one over the other?

另外,你为什么要使用一个而不是另一个?

采纳答案by sanket

If your need is to export multiple objects go with named exports(without default keyword).

如果您需要导出多个对象,请使用命名导出(无默认关键字)。

function x1(){};
function x2(){};
export {x1},{x2};  //my-module.js
import {x1},{x2} from 'my-module';

otherwise for a single export, default export works well

否则对于单个导出,默认导出效果很好

export default function x1() {};
import x1 from 'my-module';

回答by Jesse

It's easiest to just look at what the three different ES6 import/export styles compile down to in CommonJS.

最简单的方法是查看三种不同的 ES6 导入/导出样式在 CommonJS 中编译后的结果。

// Three different export styles
export foo;
export default foo;
export = foo;

// The three matching import styles
import {foo} from 'blah';
import foo from 'blah';
import * as foo from 'blah';

Roughly compiles to:

大致编译为:

exports.foo = foo;
exports['default'] = foo;
module.exports = foo;

var foo = require('blah').foo;
var foo = require('blah')['default'];
var foo = require('blah');

(Actual compiler output may differ)

(实际编译器输出可能不同)