文件:SafeString.js

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

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

export default SafeString;

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


当前回答

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

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

其他回答

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

//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

有两种不同的导出类型,命名和默认。每个模块可以有多个命名导出,但只有一个默认导出。每种类型都对应于上述类型之一。来源:MDN

命名导出

export class NamedExport1 { }

export class NamedExport2 { }

// Import class
import { NamedExport1 } from 'path-to-file'
import { NamedExport2 } from 'path-to-file'

// OR you can import all at once
import * as namedExports from 'path-to-file'

默认导出

export default class DefaultExport1 { }

// Import class
import DefaultExport1 from 'path-to-file' // No curly braces - {}

//可以为默认导入使用其他名称

import Foo from 'path-to-file' // This will assign any default export to Foo.

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

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


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

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

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

导出默认函数foo(){}

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

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

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

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