导出(导出默认)
// MyClass.ts -- using default export
export default class MyClass { /* ... */ }
主要的区别是你只能有一个默认的导出文件,你导入它像这样:
import MyClass from "./MyClass";
你可以给它起任何你喜欢的名字。例如,这工作得很好:
import MyClassAlias from "./MyClass";
命名导出(导出)
// MyClass.ts -- using named exports
export class MyClass { /* ... */ }
export class MyOtherClass { /* ... */ }
当你使用命名导出时,每个文件可以有多个导出,你需要导入括号括起来的导出:
import { MyClass } from "./MyClass";
注意:添加花括号将修复您在问题中描述的错误,并且花括号中指定的名称需要与导出的名称匹配。
或者你的文件导出了多个类,然后你可以像这样导入它们:
import { MyClass, MyOtherClass } from "./MyClass";
// use MyClass and MyOtherClass
或者你可以在这个文件中给它们其中的一个不同的名字:
import { MyClass, MyOtherClass as MyOtherClassAlias } from "./MyClass";
// use MyClass and MyOtherClassAlias
或者你可以使用* as导入所有导出的东西:
import * as MyClasses from "./MyClass";
// use MyClasses.MyClass and MyClasses.MyOtherClass here
用哪一种?
In ES6, default exports are concise because their use case is more common; however, when I am working on code internal to a project in TypeScript, I prefer to use named exports instead of default exports almost all the time because it works very well with code refactoring. For example, if you default export a class and rename that class, it will only rename the class in that file and not any of the other references in other files. With named exports it will rename the class and all the references to that class in all the other files.
它还可以很好地处理桶状文件(使用名称空间exports-export *来导出其他文件的文件)。这个答案的“例子”部分给出了一个例子。
Note that my opinion on using named exports even when there is only one export is contrary to the TypeScript Handbook—see the "Red Flags" section. I believe this recommendation only applies when you are creating an API for other people to use and the code is not internal to your project. When I'm designing an API for people to use, I'll use a default export so people can do import myLibraryDefaultExport from "my-library-name";. If you disagree with me about doing this, I would love to hear your reasoning.
也就是说,找到你更喜欢的!你可以同时使用其中一种,另一种,或者两种。
附加分
默认导出实际上是一个名为default的命名导出,所以如果文件有默认导出,那么你也可以通过执行以下操作导入:
import { default as MyClass } from "./MyClass";
请注意其他导入方式:
import MyDefaultExportedClass, { Class1, Class2 } from "./SomeFile";
import MyDefaultExportedClass, * as Classes from "./SomeFile";
import "./SomeFile"; // runs SomeFile.js without importing any exports