文件:SafeString.js

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

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

export default SafeString;

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


当前回答

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

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

其他回答

如本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

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

导出也可以写成

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

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

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

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.