文件: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.