What is the best practice for exporting?
class MyUtils {
print() {...}
convert() {...}
}
export default new MyUtils();
Or:
const myUtils = {
print() {...}
convert() {...}
}
export default myUtils;
Or something else?
Note: this should be a singleton, no more than 1 instance
Your second option should work for the singleton and that is what I use normally. From Felix's comment, I get that modules are singleton's and option 1 would also work. I am still inclined to go with the second option since the code makes my intention to use singleton very clear.
const myUtils = {
print() {...}
convert() {...}
}
export default myUtils;
Generally exporting an object as the default export is a bit of an antipattern. Your very best option would be to do
export function print() {...}
export function convert() {...}
then do
import * as utils from "./utils";
to avoid creating the object entirely, and rely on the module object itself to act as your namespace.
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