Javascript Export Class or Object

What is the best export practice?

class MyUtils {
  print() {...}
  convert() {...}
}
export default new MyUtils();

Or:

const myUtils = {
  print() {...}
  convert() {...}
}
export default myUtils;

Or something else?

Note: this must be a singleton, not more than 1 instance

+4
source share
3 answers

The second option should work for singleton, and this is what I usually use. From the Felix comment, I get the modules are singleton, and option 1 will also work. I am still inclined to go with the second option, as the code makes my intention to use singleton very clear.

const myUtils = {
  print() {...}
  convert() {...}
}

export default myUtils;
+2
source

Usually exporting an object as a default export is a bit antipattern. The best option is to do

export function print() {...}
export function convert() {...}

then do

import * as utils from "./utils";

, .

+1

If it is singleton, just export the object. You must export the class as shown below, and only if you use it more than once. (The point of the class in the end is that it should function as a template to create multiple objects)

export default class MyUtils {
  print() {...}
  convert() {...}
}
-1
source

Source: https://habr.com/ru/post/1651084/


All Articles