文件:SafeString.js

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

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

export default SafeString;

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


当前回答

导出默认值用于导出单个类、函数或原语。

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

阅读更多信息

其他回答

ES6中有两种出口:

命名导出-例如,导出函数func(){}是一个名为func的命名导出。可以使用import{exportName}从“module”;导入命名模块;。在这种情况下,导入的名称应与导出的名称相同。要导入示例中的func,必须使用import{func}from'module';。一个模块中可以有多个命名导出。

默认导出-是将从模块导入的值,如果您使用简单的import语句import X from'module'。X是将在本地为指定包含该值的变量指定的名称,它不必像原始导出那样命名。只能有一个默认导出。

模块可以同时包含命名导出和默认导出,并且可以使用“module”;中的import defaultExport、{namedExport1、namedExport3等…}将它们一起导入;。

有两种不同的导出类型,命名和默认。每个模块可以有多个命名导出,但只有一个默认导出。每种类型都对应于上述类型之一。来源: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中定义。

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

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

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

导出也可以写成

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