elmonty
elmonty

Reputation: 2444

Converting IIFE to ES6 module: export a single parent object or individual functions?

I have a Javascript file that contains an IIFE. This IIFE returns an object with many utility methods. If I want to convert this to an ES6 module, should I export the containing object or should I put all the functions at the top level of the module and export each of them separately?

It seems that the only way to namespace a set of functions with ES6 modules is to do it in the import statement, rather than the export statement. This seems backwards to me. If the module is imported in multiple places, doesn't each importing module have to duplicate the definition of the namespace? And if the import is done without a namespace, all the functions being imported could conflict with those from another module. Is that accurate?

So what's the best way to convert an IIFE like this to an ES6 module?

const utility = (function() {

  function shuffle(array) {
    ..
  }

  function areArraysEqual(array1, array2) {
    ..
  }

  // more functions here

  return {
    shuffle,
    areArraysEqual,
  }
})();

Upvotes: 1

Views: 179

Answers (1)

Felix Kling
Felix Kling

Reputation: 816552

should I export the containing object or should I put all the functions at the top level of the module and export each of them separately?

That's really up to you but I'd say it's more common to have export helper functions individually for these kind of utility modules which this seems to be. For example, it's more common to import individual functions from lodash than to import all of lodash. In the age of bundlers you want to give the caller/importer fine-grained control over what they need.

It seems that the only way to namespace a set of functions with ES6 modules is to do it in the import statement, rather than the export statement.

If you disregard exporting a whole object as "namespace" then yes.

This seems backwards to me. If the module is imported in multiple places, doesn't each importing module have to duplicate the definition of the namespace?

No. They can import only the exports they need, there is no need to import everything. But even if they do, doing something like

import * as Foo from 'utils'

multiple times isn't too bad.

And if the import is done without a namespace, all the functions being imported could conflict with those from another module. Is that accurate?

Yes, but you can alias imports:

import {helper} from 'utils'
import {helper as urlHelper} from 'url-utils'

So what's the best way to convert an IIFE like this to an ES6 module?

Make individual exports and let the consumer decide how to use the module.

Upvotes: 1

Related Questions