文件:SafeString.js

// Build out our basic SafeString type
function SafeString(string) {
  this.string = string;
}

SafeString.prototype.toString = function() {
  return "" + this.string;
};

export default SafeString;

我以前从未见过导出默认。对于出口默认值,有什么更容易理解的等效内容吗?


当前回答

在我看来,默认导出的重要之处在于它可以用任何名称导入!

如果有一个文件foo.js,它将导出默认值:

导出默认函数foo(){}

可以使用以下方法在bar.js中导入:

从“foo”导入栏import Bar from'foo'//或您希望分配给此导入的任何其他名称

其他回答

它是ES6模块系统的一部分,如本文所述。该文档中还有一个有用的示例:

如果模块定义了默认导出://foo.js导出默认函数(){console.log(“hello!”)}然后可以通过省略大括号来导入默认导出:从“foo”导入foo;foo();//你好


更新:截至2015年6月,模块系统在§15.2中定义,尤其是导出语法在ECMAScript 2015规范的§15.2.3中定义。

导出默认函数(){}可以在函数没有名称时使用。一个文件中只能有一个默认导出。另一种方法是命名导出。

本页详细介绍了导出默认值以及我发现非常有用的模块的其他详细信息。

导出默认值用于从脚本文件导出单个类、函数或原语。

导出也可以写成

export default function SafeString(string) {
  this.string = string;
}

SafeString.prototype.toString = function() {
  return "" + this.string;
};

这用于在另一个脚本文件中导入此函数

在app.js中说,你可以

import SafeString from './handlebars/safe-string';

关于出口

顾名思义,它用于从脚本文件或模块导出函数、对象、类或表达式

实用程序.js

export function cube(x) {
  return x * x * x;
}
export const foo = Math.PI + Math.SQRT2;

这可以导入并用作

应用程序.js

import { cube, foo } from 'Utilities';
console.log(cube(3)); // 27
console.log(foo);    // 4.555806215962888

Or

import * as utilities from 'Utilities';
console.log(utilities.cube(3)); // 27
console.log(utilities.foo);    // 4.555806215962888

当使用导出默认值时,这要简单得多。脚本文件只导出一件事。立方体.js

export default function cube(x) {
  return x * x * x;
};

并用作应用程序.js

import Cube from 'cube';
console.log(Cube(3)); // 27

如本MDN页所述

有两种不同的导出类型,命名和默认。你可以每个模块有多个命名导出,但只有一个默认值export[…]命名导出对于导出多个值非常有用。在期间导入时,必须使用相应的对象。但可以使用任何名称导入默认导出

例如:

let myVar; export default myVar = 123; // in file my-module.js

import myExportedVar from './my-module' //  we have the freedom to use 'import myExportedVar' instead of 'import myVar' because myVar was defined as default export

console.log(myExportedVar);        // will log 123

导出默认值用于从文件中仅导出一个值,该文件可以是类、函数或对象。默认导出可以使用任何名称导入。

//file functions.js

export default function subtract(x, y) {
  return x - y;
}

//importing subtract in another file in the same directory
import myDefault from "./functions.js";

在导入的文件中,减法函数可以称为myDefault。

导出默认值还会创建一个回退值,这意味着如果您尝试导入命名导出中不存在的函数、类或对象。将提供默认导出提供的回退值。

有关详细说明,请访问https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export