What is the difference in Typescript between export
and default export
. In all the tutorials I see people export
ing their classes and I cannot compile my code if I don't add the default
keyword before exporting.
Also, I couldn't find any trace of the default export keyword in the official typescript documentation.
export class MyClass {
collection = [1,2,3];
}
Does not compile. But:
export default class MyClass {
collection = [1,2,3];
}
Does.
The error is: error TS1192: Module '"src/app/MyClass"' has no default export.
This question is related to
javascript
typescript
ecmascript-6
Here's example with simple object exporting.
var MyScreen = {
/* ... */
width : function (percent){
return window.innerWidth / 100 * percent
}
height : function (percent){
return window.innerHeight / 100 * percent
}
};
export default MyScreen
In main file (Use when you don't want and don't need to create new instance) and it is not global you will import this only when it needed :
import MyScreen from "./module/screen";
console.log( MyScreen.width(100) );
Named export
In TS you can export with the export
keyword. It then can be imported via import {name} from "./mydir";
. This is called a named export. A file can export multiple named exports. Also the names of the imports have to match the exports. For example:
// foo.js file
export class foo{}
export class bar{}
// main.js file in same dir
import {foo, bar} from "./foo";
The following alternative syntax is also valid:
// foo.js file
function foo() {};
function bar() {};
export {foo, bar};
// main.js file in same dir
import {foo, bar} from './foo'
Default export
We can also use a default export. There can only be one default export per file. When importing a default export we omit the square brackets in the import statement. We can also choose our own name for our import.
// foo.js file
export default class foo{}
// main.js file in same directory
import abc from "./foo";
It's just JavaScript
Modules and their associated keyword like import
, export
, and export default
are JavaScript constructs, not typescript. However typescript added the exporting and importing of interfaces and type aliases to it.
I was trying to solve the same problem, but found an interesting advice by Basarat Ali Syed, of TypeScript Deep Dive fame, that we should avoid the generic export default
declaration for a class, and instead append the export
tag to the class declaration. The imported class should be instead listed in the import
command of the module.
That is: instead of
class Foo {
// ...
}
export default Foo;
and the simple import Foo from './foo';
in the module that will import, one should use
export class Foo {
// ...
}
and import {Foo} from './foo'
in the importer.
The reason for that is difficulties in the refactoring of classes, and the added work for exportation. The original post by Basarat is in export default
can lead to problems
Source: Stackoverflow.com