I was looking at this code where a class instance is exported in a little bit weird way.
Providing a snipped. It is exported as follows:
class RegisterStore {
@observable success = false
@observable failure = false
@observable errors = {}
...
}
export default new RegisterStore()
export { RegisterStore }
And it is imported as follows in index.js:
import registerStore from './stores/RegisterStore'
...
const stores = {
registerStore
...
}
Why are there two exports at the end of the first code? Is export default new RegisterStore()
AND const NewRegisterStore = new RegisterStore(); export default NewRegisterStore
are equivalent?
Use named exports to export a class in JavaScript, e.g. export class Employee {} . The exported class can be imported by using a named import as import {Employee} from './another-file. js' . You can use as many named exports as necessary in a file.
The export declaration is used to export values from a JavaScript module. Exported values can then be imported into other programs with the import declaration or dynamic import.
By the use of an export keyword, we can export class, function, file, interface, type, etc. in TypeScript. By default it comes up with all the classes or interfaces we create in TypeScript, after this we can easily import these files using the 'import' keyword.
No export default new RegisterStore() and export { RegisterStore }
are not equal. In export { RegisterStore }
you are exporting the class as a part of an export object while in export default new RegisterStore()
you are exporting instance of class.
Further. export default new RegisterStore()
should be enough to work fine. Exporting again line is useless until you dont want to import multiple variables from the same file. In that case it would be like:
export new RegisterStore();
export const anotherVariable = "TESTTEST";
and import like:
import {RegisterStore, anotherVariable} from './stores/RegisterStore';
Further to your last query: NO
export default new RegisterStore() AND
export default const RegisterStore = new RegisterStore() are equivalent?
are not equivalent too.
Firstly export default const RegisterStore = new RegisterStore()
throws error because RegisterStore
is already declared as class and you are again declaring it with const.
Secondly:
export default const NewRegisterStore = new RegisterStore()
is also wrong because default exports have to be either exported as anonymous or the variables have to be declared first before exporting.
For your example it should be like:
let NewRegisterStore; export default NewRegisterStore = new RegisterStore();
So:
export default new RegisterStore() AND
let NewRegisterStore; export default NewRegisterStore = new RegisterStore(); are equivalent
Please read more about "named export" and "export default" here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With