In case of utility module, I can have either class with static methods or just export methods. I think the first solution is better, though I saw a lot of implementations with second option. Are there any "nuances" here which I am not considering?
The Export function is an idea used in economic theories to measure exports. The total amount of exports, E, in a nation is mainly affected by two variables, see import, the total foreign absorption and the real exchange rate.
Use named exports to export a component in React, e.g. export function Button() {} . The exported component can be imported by using a named import as import {Button} from './another-file. js' . You can use as many named exports as necessary in a file.
Exports without a default tag are Named exports. Exports with the default tag are Default exports. Using one over the other can have effects on your code readability, file structure, and component organization. Named and Default exports are not React-centric ideas.
When we want to export a single class/variable/function from one module to another module, we use the module. exports way. When we want to export multiple variables/functions from one module to another, we use exports way. 2.
I would argue that a class with static methods is better for the following reasons:
If your class name is Utils
, all imports will by default import it as Utils
too. With exported functions however, they could be imported as Utils
yet that would only be a convention , one that likely won't be the case in all the different places.
A class named Utils
in a file named utils.js
with all the utility methods neatly grouped together is aesthetically more pleasant than flat functions defined all over the place.
A class could have properties
that are used among its methods, for this you'd need @babel/plugin-proposal-class-properties though. Again, much nicer than variables defined all over the place.
Exporting methods is safer because you don't give access to class properties. Note also that in javascrpt the concept of class does not have a lot of sense, it's been introduced to make feel more confortable developers with oo languages background. Try to work with Object prototyping instead.
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