Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...