ES6 modules: Export single class of static methods OR multiple individual methods

A class of just static methods feels like a bit of a ‘code smell’

Yes indeed. You don’t need a class structure here! Just export a normal “module” object:

//------ myMethods.js ------

export default {
  myMethod1() {
    console.log('foo'); 
  },
  myMethod2(args...) {
    console.log('bar'); 
  }  
};

I do recommend your second approach with multiple exports, though.

exporting everything individually does feel a bit verbose

Well, you don’t need any wrapper structure, so I’d say it’s less boilerplate. You just have to explicitly tag everything that you want to be exported, which is not a bad thing.

* as syntax is my preferred method as it allows you to use the dot notation (referencing both the module AND the method) aiding code readability.

That’s very much personal preference, and does depend on the type of code you are writing. Sometimes conciseness is superior, but the ability to explicitly reference the module can be helpful as well. Notice that namespace imports using * as and default-imported objects are very similar here, though only named exports allow you to directly reference them via import {myMethod1, myMethod2}. So better leave the choice to those that import your module.

Does this have any performance implications?

Not much. Current ES6 implementations are not yet aiming for performance optimisations anyway.

In general, static identifiers are easier to resolve and optimise than property accesses[1], multiple named exports and partial imports could theoretically make JIT faster, and of course smaller files need less time to load if unused exports are removed during bundling. See here for details. There hardly will be noticeable performance differences, you should use what is better maintainable.

[1]: module namespaces (import * as ns) are static as well, even if ns.… looks like a dynamic property access

Leave a Comment