0

I am building a set of utilities for my 'own use' app. Using ES2015, I wonder where I should create the utility functions as independent of each other within the module, ala =>

export const doSomething = () => {
 ... }

export const doSomethingElse = () => {
 ... }

My question is, is there any need for going the old fashioned way of creating a main object & then extending that object with all the utility functions? Ala =>

export const mainObj = function(){
 ... }

mainObj.prototype.doSomething = function(){
 ... }

mainObj.prototype.doSomethingElse = function(){
 ... }

Many thanks

Kayote
  • 14,579
  • 25
  • 85
  • 144

2 Answers2

1

If you export functions individually then a bundler / build tool can use tree shaking. That is excluding unused functions from the final script and thereby reducing the code size.

That's not possible (or at least difficult) when you export an object, because properties can be referenced dynamically. So a tool cannot say for sure if a function will be used or not.

If you prefer having an object you can always import * which has a similar effect, but prevents tree shaking.

a better oliver
  • 26,330
  • 2
  • 58
  • 66
  • Thats a wonderful point. And as I am using Webpack, it makes sense. I wanted to find out if there are any benefits to still going the old way, I guess, there aren't. – Kayote Mar 14 '17 at 13:17
0

You can do this in a few ways. Manipulating prototypes is definitely not the clean way to go. You probably just want plain objects OR classes.

This is how I usually structure modules that expose free functions:

// Either 
const foo = function foo (...args) {
  return args;
};

module.exports = {
  foo
  // …
};

// Or if you do not need to reference other functions in 
// the same module
module.exports = {
  foo (...args) {
    return args;
  }
  // …
};
Alex Pánek
  • 413
  • 2
  • 8