Skip to content
Advertisement

es2015 modules – how to name exports dynamically

In this example react-hyperscript is curried and exposes a set of default functions, so h('div', props, children) becomes div(props, children).

import hyperscript from 'react-hyperscript';
import {curry} from 'lodash';

const isString = v => typeof v === 'string' && v.length > 0;
const isSelector = v => isString(v) && (v[0] === '.' || v[0] === '#');

const h = curry(
  (tagName, first, ...rest) =>
    isString(tagName) && isSelector(first) ?
      hyperscript(tagName + first, ...rest) :
      hyperscript(tagName, first, ...rest)
);

const TAG_NAMES = [
  'a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', // ...
];

TAG_NAMES.forEach(tagName =>
  Object.defineProperty(h, tagName, {
    value: h(tagName),
    writable: false,
  })
);

export default h;

In another module:

import h, {div} from 'lib/h';

console.log(
  h,        // h
  div,      // undefined <- problem!
  h('div'), // div
  h.div     // div
)

This can be resolved by appending this to the example (zip from lodash):

const {
  a, abbr, address, area, // ...
} = zip(
  TAG_NAMES,
  TAG_NAMES.map(h)
)

export {
  a, abbr, address, area, // ...
}

But this solution isn’t very elegant, does anybody know a better alternative?

Answer

how to name exports dynamically

You can’t. import and export statements are specifically designed this way because they have to be statically analyzable, i.e. the import and export names have to be known before the code is executed.

If you need something dynamic then do what you are already doing: Export a “map” (or object). People can still use destructuring to just get what they want:

const {div} = h;
Advertisement