es2015模块 - 如何动态地命名输出 [英] es2015 modules - how to name exports dynamically

查看:82
本文介绍了es2015模块 - 如何动态地命名输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个例子中, react-hyperscript 是curried并公开了一组默认函数,所以 h('div',道具,孩子)成为 div(道具,孩子)

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;

在另一个模块中:

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

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

这可以通过将其附加到示例(来自lodash的zip):

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?

推荐答案


如何动态地输出export

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.

如果你需要动态的东西,然后做你已经在做的事情:导出一个map(或物体)。人们仍然可以使用解构来获得他们想要的东西:

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;

这篇关于es2015模块 - 如何动态地命名输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆